I'm running the following Java code on a laptop with 2.7 GHz Intel Core i7. I intended to let it measure how long it takes to finish a loop with 2^32 iterations, which I expected to be roughly 1.48 seconds (4/2.7 = 1.48).

我使用2.7 GHz的Intel Core i7在笔记本电脑上运行以下Java代码。我打算让它测量需要多长时间完成一个循环2 ^ 32个迭代,我预计将大约1.48秒(4/2.7 = 1.48)。

But actually it only takes 2 milliseconds, instead of 1.48s. I'm wondering if this is a result of any JVM optimization underneath?

但实际上只需要2毫秒,而不是1。48秒。我想知道这是否是JVM优化的结果?

public static void main(String[] args)
{
    long start = System.nanoTime();

    for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++){
    }
    long finish = System.nanoTime();
    long d = (finish - start) / 1000000;

    System.out.println("Used " + d);
}

6 个解决方案

#1


105

There are one of two possibilities going on here:

这里有两种可能性:

  1. The compiler realized that the loop is redundant and doing nothing so it optimized it away.

    编译器意识到循环是冗余的,什么也不做,因此它对循环进行了优化。

  2. The JIT (just-in-time compiler) realized that the loop is redundant and doing nothing, so it optimized it away.

    JIT(即时编译器)意识到循环是冗余的,什么都不做,因此对它进行了优化。

Modern compilers are very intelligent; they can see when code is useless. Try putting an empty loop into GodBolt and look at the output, then turn on -O2 optimizations, you will see that the output is something along the lines of

现代的编译器非常智能;他们可以看到代码什么时候是无用的。尝试在GodBolt中放入一个空循环,并查看输出,然后打开-O2优化,您将看到输出是沿着

main():
    xor eax, eax
    ret

I would like to clarify something, in Java most of the optimizations are done by the JIT. In some other languages (like C/C++) most of the optimizations are done by the first compiler.

我想澄清一点,在Java中,大多数优化都是由JIT完成的。在其他一些语言(比如C/ c++)中,大多数优化都是由第一个编译器完成的。

更多相关文章

  1. java开发编译器:中间语言格式
  2. 《深入理解Java虚拟机》:HotSpot虚拟机内的即时编译器

随机推荐

  1. 上优酷土豆,再也不用看广告啦!
  2. 豆瓣开源的那些神库
  3. Spring Cloud Security:Oauth2结合JWT使用
  4. Spring Cloud Security:Oauth2实现单点登
  5. String还有长度限制?是多少?
  6. 仅需四步,整合SpringSecurity+JWT实现登录
  7. Spring Cloud Alibaba:Nacos 作为注册中心
  8. 百度亮了,Python帮你上Google
  9. 使用Jenkins一键打包部署SpringBoot应用,
  10. 你还在代码里做读写分离么,试试这个中间件