Reputation: 4673
// Hideously slow program! Can you spot the object creation?
Long sum = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
end = System.currentTimeMillis();
System.out.println("Long sum took: " + (end - start) + " milliseconds");
long sum2 = 0L;
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum2 += i;
}
end = System.currentTimeMillis();
System.out.println("long sum took: " + (end - start) + " milliseconds");
Hi, I am reading Effective Java and in Item 6:Avoid creating unnecessary objects
, there is an example suggesting primitives to boxed primitives to avoid unnecessary object creation.
The author says, "Changing the declaration of sum from Long to long reduces the runtime from 43 seconds to 6.8 seconds on my machine." and continues, "The lesson is clear: prefer primitives to boxed primitives, and watch out for unintentional autoboxing".
But when I run it on my machine, the primitive version is slower than the boxed one.
The output of the program above:
Long sum took: 5905 milliseconds
long sum took: 7013 milliseconds
The results are not as expected as the author says, "The variable sum is declared as a Long instead of a long, which means that the program constructs about 2^31 unnecessary Long instances (roughly one for each time the long i is added to the Long sum)".
Why is using primitive slower than using object?
Upvotes: 0
Views: 1866
Reputation: 2510
You didn't reset the starting point for the second measurement. The primitive performance is actually the time difference of your two values (which is obviously better than the wrapper's). Try this:
// Hideously slow program! Can you spot the object creation?
Long sum = 0L;
start = System.currentTimeMillis();
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum += i;
}
end = System.currentTimeMillis();
System.out.println("Long sum took: " + (end - start) + " milliseconds");
long sum2 = 0L;
// reset start!!
start = System.currentTimeMillis();
for (long i = 0; i < Integer.MAX_VALUE; i++) {
sum2 += i;
}
end = System.currentTimeMillis();
System.out.println("long sum took: " + (end - start) + " milliseconds");
Upvotes: 10