Which of these pieces of code is faster in Java?

前端 未结 16 2024
囚心锁ツ
囚心锁ツ 2020-11-30 04:25

a) for(int i = 100000; i > 0; i--) {}

b) for(int i = 1; i < 100001; i++) {}

The answer is t

16条回答
  •  借酒劲吻你
    2020-11-30 04:55

    There are really only two ways to answer this question.

    1. To tell you that it really, really doesn't matter, and you're wasting your time even wondering.

    2. To tell you that the only way to know is to run a trustworthy benchmark on your actual production hardware, OS and JRE installation that you care about.

    So, I made you a runnable benchmark you could use to try that out here:

    http://code.google.com/p/caliper/source/browse/trunk/test/examples/LoopingBackwardsBenchmark.java

    This Caliper framework is not really ready for prime time yet, so it may not be totally obvious what to do with this, but if you really care enough you can figure it out. Here are the results it gave on my linux box:

         max benchmark        ns
           2  Forwards         4
           2 Backwards         3
          20  Forwards         9
          20 Backwards        20
        2000  Forwards      1007
        2000 Backwards      1011
    20000000  Forwards   9757363
    20000000 Backwards  10303707
    

    Does looping backwards look like a win to anyone?

提交回复
热议问题