Which of these pieces of code is faster in Java?

前端 未结 16 2066
囚心锁ツ
囚心锁ツ 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 05:05

    Typically real code will run faster counting upwards. There are a few reasons for this:

    • Processors are optimised for reading memory forwards.
    • HotSpot (and presumably other bytecode->native compilers) heavily optimise forward loops, but don't bother with backward loops because they happen so infrequently.
    • Upwards is usually more obvious, and cleaner code is often faster.

    So happily doing the right thing will usually be faster. Unnecessary micro-optimisation is evil. I haven't purposefully written backward loops since programming 6502 assembler.

提交回复
热议问题