0

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:

  1. i++ boxes i + 1 to Integer
  2. sum1 + 1 is boxed to Integer

unboxing:

  1. i < length unboxes i to int

Am I correct for above? And how can I programmatically count the number of boxing and unboxing operations?

A1122
  • 1,324
  • 3
  • 15
  • 35
  • `i < length` and `i++` are going to execute 1000000000 times and `sum1 = sum1 + 1;` is going to execute (1000000000 - 1). Hopefully you can see the pattern. – Yoshikage Kira Jun 13 '21 at 22:07

1 Answers1

0

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;

Iva Levak
  • 27
  • 3