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!