Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Primitives and Primitive Wrappers

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?

like image 453
Venk K Avatar asked Dec 20 '22 00:12

Venk K


2 Answers

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.

like image 141
Stephen C Avatar answered Jan 05 '23 13:01

Stephen C


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

like image 34
Narendra Pathai Avatar answered Jan 05 '23 14:01

Narendra Pathai