Why do we prefer primitives and boxed primitives in Java
I'm reading the second edition of valid Java and page 23
// Hideously slow program! Can you spot the object creation public static void main(String[] args) { Long sum = 0L; for(long i=0; i<=Integer.MAX_VALUE; i++){ sum += i; } System.out.println(sum) }
The author said that the above code unnecessarily generated 2 ^ 31 object instances Why does sum = I generate a new object? If I change the declaration to
sum = sum + 1
No such side effects?
Solution
Try to rewrite what others say in a clearer way:
The problem with sum is that long is a reference type; In other words, it is some kind of object Objects live on heaps; They are created by the JVM (using "new" and constructors) and "managed" by the garbage collector
The auto boxing feature allows you to use long variables of this reference type, just like long variables of basic type
But the long object is immutable; Once created, its value will never change But the whole loop is about constantly changing a value (by incrementing the counter)! Therefore, to increment the counter, you must get the value of the "current" long object; Add 1; And fill it in the next long object Again and again
So what your program does here is: always create garbage In other words: create those long objects; Use once (retrieve their value); Then they are "forgotten" (because they are not mentioned anywhere) Therefore, they are immediately eligible for garbage collection
Meaning: there are actually two effects on Performance:
>Unnecessary object creation [quite cheap in Java, but still "more expensive" than simple calculation of long values; the latter may be just one or two CPU instructions; and object creation will lead to memory access and quite a few CPU operations!] > Create objects requiring garbage collection at high speed