I have a loop like this
int length = 1000000000;
Integer sum1 = 0;
for (Integer i = 0; i < length; i++) {
sum1 = sum1 + 1;
}
System.out.println(sum1);
How do I count the number of boxing and unboxing operations here? Here are what I guess to be boxing and unboxing
boxing:
i++boxesi + 1toIntegersum1 + 1is boxed to Integer
unboxing:
i < lengthunboxesitoint
Am I correct for above? And how can I programmatically count the number of boxing and unboxing operations?
If sum1 is always incremented by 1 and at beginning of program is always zero, then sum1 is actually the number of boxed operation performed with sum1. Operation on sum1 is shorter:
--> sum1=sum1+1;-->sum1+=1-->sum1++;
So if sum1 is number of boxed operation performed with sum1, then we can assume that with i++ operation number of boxed operation on i is actually i. For loop always checks condition
i<length
, so we know it will check this length times. You might think that it iterates through lenth-1 times, but actually it checks and last, not fullfiled condition.
So we may conclude that:
number_unboxed_operations=length, number_boxed_operations=i+sum1.
If operation on sum1 is indeed different(sum1+=2), we can ask ourselfs how much time will condition be true.
Condition will be true until i==length so for sum1 operation will be performed lenth-1 times;