While not directly related to this question, this is how you would correctly micro benchmark the code using Caliper. Below is a modified version of your code so that it will run with Caliper. The inner loops had to be modified some so that the VM will not optimize them out. It is surprisingly smart at realizing nothing was happening.
There are also a lot of nuances when benchmarking Java code. I wrote about some of the issues I ran into at Java Matrix Benchmark, such as how past history can effect current results. You will avoid many of those issues by using Caliper.
- http://code.google.com/p/caliper/
Benchmarking issues with Java Matrix Benchmark
public class PerformanceCheck extends SimpleBenchmark {public int timeFirstCase(int reps) { List<PerformanceCheck> removeList = new LinkedList<PerformanceCheck>(); removeList.add( new PerformanceCheck()); int ret = 0; for( int i = 0; i < reps; i++ ) { if (removeList.size() > 0) { if( testFunc(i) ) ret++; } } return ret;}public int timeSecondCase(int reps) { List<PerformanceCheck> removeList = new LinkedList<PerformanceCheck>(); removeList.add( new PerformanceCheck()); int ret = 0; for( int i = 0; i < reps; i++ ) { if (removeList.size() == 0) { if( testFunc(i) ) ret++; } } return ret;}private static boolean testFunc(int test) { return 5 > test;}public static void main(String[] args) { Runner.main(PerformanceCheck.class, args);}}
OUTPUT:
0% Scenario{vm=java, trial=0, benchmark=FirstCase} 0.60 ns; σ=0.00 ns @ 3 trials50% Scenario{vm=java, trial=0, benchmark=SecondCase} 1.92 ns; σ=0.22 ns @ 10 trials benchmark ns linear runtime FirstCase 0.598 =========SecondCase 1.925 ==============================vm: javatrial: 0




