0

I read this in an article. But the answer given here is not clear..

  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.
Kevin Rave
  • 13,876
  • 35
  • 109
  • 173
  • 1
    And this discussion may help you http://stackoverflow.com/questions/7854808/hotspot-jit-optimizations – kosa Nov 16 '12 at 22:49
  • It is called optimization not caching (This varies from JVM to JVM). This link may get you started http://docs.oracle.com/cd/E15289_01/doc.40/e15058/underst_jit.htm – kosa Nov 16 '12 at 22:53
  • this will also help you , http://stackoverflow.com/questions/7271147/java-how-much-time-does-an-empty-loop-use – Jimmy Nov 17 '12 at 00:47

1 Answers1

0

Java is a high level language, so there will be deference between the code you write, and the code that is generated by the compiler. The compiler and JVM are trying to optimize your code. The first for will not be executed because it doesn't do something, and it doesn't iterate more than 10000 times. The second for does iterate, but JVM execute it because it iterate over 10000 times.

cristi
  • 361
  • 3
  • 9