Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Running in standard configured eclipse, does the compiler optimize the code

800281Mar 16 2009 — edited Mar 16 2009
Hello,

I was playing with benchmarks in a standard configured eclipse (idk1.6.0_10).
And in this forum I've read a lot that micro optimization is not needed as the compiler does that for you.
But I got the following results:
^= time: 1813
=! time: 3172
when running this code
public class ShiftTrue {
	public static void main(String[] args) {
		boolean tmp=true;
		long startTime = System.currentTimeMillis();
		
		for (int i=0;i<Integer.MAX_VALUE;i++){
			tmp^=true;
		}
		System.out.println("^= time: "+
				(System.currentTimeMillis()-startTime));
		
		startTime = System.currentTimeMillis();
		for (int i=0;i<Integer.MAX_VALUE;i++){
			tmp=!tmp;
		}
		System.out.println("=! time: "+
				(System.currentTimeMillis()-startTime));
	}
}
So my finding is that the compiler is pretty bad at optimize as the time elapsed should have been the same.
I also have example of two other benchmarks i did.
Result:
Shifted: 62 millis
Divided: 63 millis
When running:
public class bitshift {
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		int a = 0;
		for(int i = 1; i<100000000;i++){
			a = 1029 >>> 8;
		}
		System.out.println("Shifted: "+
				(System.currentTimeMillis()-startTime)+" millis");
		startTime = System.currentTimeMillis();
		for(int i = 1; i<100000000;i++){
			a = 1029/256;
		}
		System.out.println("Divided: "+
				(System.currentTimeMillis()-startTime)+" millis");
	}
}
Time elapsed should be 0 as the loop should only be run one time.
When using "i" in the loop I got the following:
Shifted: 94 millis
Divided: 1172 millis
Code:
public class bitshift {
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		int a = 0;
		for(int i = 1; i<100000000;i++){
			a = i >>> 8;
		}
		System.out.println("Shifted: "+
				(System.currentTimeMillis()-startTime)+" millis");
		startTime = System.currentTimeMillis();
		for(int i = 1; i<100000000;i++){
			a = i/256;
		}
		System.out.println("Divided: "+
				(System.currentTimeMillis()-startTime)+" millis");
	}
}
Also pretty bad at optimize as the time elapsed should have been the same.
Are there any way to tell the compiler in eclipse to do a better job or do I have to think about those optimizations myself even if they logically should be no problem for the compiler to fix.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 13 2009
Added on Mar 16 2009
1 comment
168 views