Java – output timing problem

The following codes:

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 line 9, if the condition is true, it is allowed to print. Although the two objects are different, it will not happen. Then it takes 5000 milliseconds, and only the comment takes 5 milli. I have no reason why it takes so much time if there is no comment, because it will never be executed

Is this a branch prediction effect? Or any type of compiler optimization

Solution

The compiler optimizes dead code – in this case, the entire loop is deleted This can be done by a bytecode compiler (such as javac), or more likely by hotspot's JIT

Why does this execution still take 5 milliseconds? It doesn't have to take long Instead, you may encounter system The resolution limit of currenttimemillis() Try it with System. nanoTime() instead. Fwiw, using nanotime() is consistent with currenttimemillis() on Windows systems

How do I write a correct micro benchmark in Java? And is stopwatch benchmarking acceptable?

Further reading

> White Paper: The Java HotSpot Performance Engine Architecture > HotSpot Home Page

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>