I am trying to understand how Java primitives and wrappers work. Let us consider the following example.
Integer sum = 0;
for(int i = 0; i < 10000; ++i) {
sum += i;
}
Since Integer is immutable and a non-primitive, the statement sum += i
will be compiled as the following
sum = new Integer(sum.intValue() + i).
This would create around 10000 Integer objects (every call to new Integer
) and the cost of sum.intValue()
of unboxing the Integer to int.
Am I right?
Not exactly. In fact:
sum += i;
is equivalent to
sum = Integer.valueOf(sum.intValue() + i);
For small integer values, Integer.valueOf(int)
will return a cached Integer
object. That means that you will get somewhat less than 10,000 new Integer
objects created.
But "small" typically means -128 to +127 (IIRC) ... so the difference won't be significant.
As Louis Wasserman points out,object allocation is cheap, and garbage collection of objects that "die young" is even cheaper. Nevertheless, you shouldn't use primitive wrappers unnecessarily, and especially not in code like this.
Prefer primitive types over Boxed types when using Loop
Yes you are correct the process of boxing and unboxing, especially in a loop can serious impede performance.
But in your case you are just looping and you should NOT be using boxed primitive here and rather use int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With