I was going through "Effective Java" book by Joshua Bloch and encountered a very interesting fact discussed on performance. So I thought, I must share this with you people.
It is about how you can optimize your code tremendously by just using primitive variable.
Here we are going to do the same thing in 2 different program, one using Wrapper Long class and one using primitive long.
We will take an example of doing sum from 1 to Integer.MAX_VALUE and analyze total execution time.
Example 1: Sum using wrapper Long class.
If you execute above code snippet, total execution time will come around approximately 7 second.
Example 2: Sum using primitive long
If you execute above code snippet, total execution time will come around approximately 1 second.
Example 2 differs from example 1 just by variable declaration. It uses primitive long instead of Wrapper Long class.
So bottom line is by just using primitives, we saw huge performance gain. Here it is 6 seconds which is huge difference.
Conclusion: Always try to use primitive as much as possible over Wrapper class, because that reduces unnecessary overhead of auto boxing and un-boxing from JVM end.
It is about how you can optimize your code tremendously by just using primitive variable.
Here we are going to do the same thing in 2 different program, one using Wrapper Long class and one using primitive long.
We will take an example of doing sum from 1 to Integer.MAX_VALUE and analyze total execution time.
Example 1: Sum using wrapper Long class.
import java.util.concurrent.TimeUnit;
public class LongTest {
public static void main(String[] args) {
Long sum= new Long(0);
long startTime = System.nanoTime();
for(long i=0; i<Integer.MAX_VALUE;i++){
sum+=i;
}
long endTime= System.nanoTime();
System.out.println(sum+" in "+TimeUnit.SECONDS.convert(endTime-startTime, TimeUnit.NANOSECONDS)+" seconds");
}
}
If you execute above code snippet, total execution time will come around approximately 7 second.
Example 2: Sum using primitive long
import java.util.concurrent.TimeUnit;
public class LongTest {
public static void main(String[] args) {
long sum=0;
long startTime = System.nanoTime();
for(long i=0; i<Integer.MAX_VALUE;i++){
sum+=i;
}
long endTime= System.nanoTime();
System.out.println(sum+" in "+TimeUnit.SECONDS.convert(endTime-startTime, TimeUnit.NANOSECONDS)+" seconds");
}
}
If you execute above code snippet, total execution time will come around approximately 1 second.
Example 2 differs from example 1 just by variable declaration. It uses primitive long instead of Wrapper Long class.
So bottom line is by just using primitives, we saw huge performance gain. Here it is 6 seconds which is huge difference.
Conclusion: Always try to use primitive as much as possible over Wrapper class, because that reduces unnecessary overhead of auto boxing and un-boxing from JVM end.
No comments:
Post a Comment