the following code:
String str1="asdfavaxzvzxvc";
String str2="werwerzsfaasdf";
Object c=str1;
Object d=str2;
System.out.println(c);
long time1=System.currentTimeMillis();
for(int i=0;i<1000000000;i++){
if(c.equals(d)){
//System.out.println("asfasdfasdf"); // line 9
}
}
long time2=System.currentTimeMillis();
System.out.println("time taken in this is "+(time2-time1));
When I uncomment the line 9, that is let print if condition is true, though never it is going to happen since both object are not equal , then it takes 5000+ milli-seconds, and to my surprise by just commenting it takes only 5 milli-seconds, I am not getting the reason, why it takes so much time if it is not commented, since it’s never going to get executed…
Is this some sort of branch prediction effect ? or any sort of compiler optimization
The compiler optimizes away dead code — in this case, the entire loop is removed. This might be done by the bytecode compiler (e.g.
javac) or, more likely, by HotSpot‘s JIT.Why does it still take a whopping 5 ms for this to execute? It doesn’t necessarily take all that long. Instead, you might be hitting the resolution limit on
System.currentTimeMillis(). Try it withSystem.nanoTime()instead. FWIW, usingnanoTime()agrees withcurrentTimeMillis()on my Windows system.You might be interested in reading How do I write a correct micro-benchmark in Java? and Is stopwatch benchmarking acceptable?
Further reading