Reason why the time taken to execute below code snippets differ a lot?

Viewed 76

Consider the code snippets below and the time taken to execute them -

 public static void main(String[] args) {
    Long startTime = System.currentTimeMillis();
    long sum = 0L;
    for(int i = 0; i< Integer.MAX_VALUE; i++){
        sum+=i;
    }
    Long timeDiff = (System.currentTimeMillis() - startTime) / 1000;
    System.out.println("Time Difference : " + timeDiff + "secs");
}

Output -

Time Difference : 0secs

public static void main(String[] args) {
    Long startTime = System.currentTimeMillis();
    Long sum = 0L;
    for(int i = 0; i< Integer.MAX_VALUE; i++){
        sum+=i;
    }
    Long timeDiff = (System.currentTimeMillis() - startTime) / 1000;
    System.out.println("Time Difference : " + timeDiff + "secs");
}

Output -

Time Difference : 8secs

public static void main(String[] args) {
    Long startTime = System.currentTimeMillis();
    Long sum = 0L;
    for(Long i = 0L; i< Integer.MAX_VALUE; i++){
        sum+=i;
    }
    Long timeDiff = (System.currentTimeMillis() - startTime) / 1000;
    System.out.println("Time Difference : " + timeDiff + "secs");
}

Output -

Time Difference : 16secs

As per my understanding, it's happening because of every time object creation of Long Object, I am not sure how exactly this is happening. Tried looking into byte code didn't help much. Help me understand how exactly things are internally happening?

Thanks in advance!

2 Answers

The "++" and "+=" operators are only defined for primitives.

Hence, when you apply them to a Long, an unboxing must take place before the operator is evaluated and then a boxing must take place to store the result.

The boxing probably costs more than the unboxing, since unboxing requires just a method call, while boxing requires object instantiation.

Each boxing involves the creation of a Long instance. Your loop has Integer.MAX_VALUE iterations, so the second loop creates over 2 billion Long objects (one for each sum+=i operation) while the third loop creates over 4 billion Long objects (one for each i++ operation and one for each sum+=i operation). These objects have to be instantiated and later garbage collected. That costs time.

Plausible causes:
- Too many object creations leading to GC activity at times.
- Too many boxing and unboxing of Wrapper to primitive and vice versa.

Related