0

我在一篇文章中读到了这一点。但是这里给出的答案并不清楚..

  1. is it true?
  2. Can anyone explain it better?
  3. Is there a document that explains java / JVM caching mechanism overall?


  **Which one is faster in Java ?**

  for(int i = 100000; i > 0; i--) {}
  for(int i = 1; i < 100001; i++) {}


  Answer: Which ever is run second with be fastest. The server JVM can detect and 
  eliminate loops which don't do anything. A method with either loop is compiled when 
  the loop iterates about 10,000 times. (Based on -XX:CompileThreshold=10000) The first 
  loop will take time to detect it doesn't do anything, however the second will have been
  compiled.
4

1 回答 1

0

Java 是一种高级语言,因此您编写的代码与编译器生成的代码之间会有差异。编译器和 JVM 正在尝试优化您的代码。第一个 for 不会被执行,因为它没有做任何事情,并且它不会迭代超过 10000 次。第二个 for 确实迭代,但 JVM 执行它,因为它迭代超过 10000 次。

于 2012-11-16T23:03:34.063 回答