Look at this Java code:
class PerformanceTest2{
public static void main(String args[]){
Long sum = 0L;
for(int i=0;i<Integer.MAX_VALUE;i++)
sum += i;
System.out.println("Sum = " + sum);
}
}
It is observed that it takes longer for this code since sum is ‘Long’ & not ‘long’. So in every iteration what happens is:
sum = new Long(sum.longValue() + i); (for sum+=i;)
So, a new object is created every time. Doesn’t Java support C++ like feature of returning a reference so that we could’ve written (possibly):
sum.longValue() += i;
possibly not having to create sum object every time around the loop? Am I right?
Well, it doesn’t call the constructor. It uses:
The wrapper objects are deliberately immutable – they could easily have been designed to be mutable, but immutability is often a very useful feature. If you want to write your own mutable wrapper type, you’re very welcome to – at which point you could have code such as:
Or possibly: