Which of these pieces of code is faster in Java?

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

    On many compilers, the machine instructions emitted for a loop going backwards, are more efficient, because testing for zero (and therefore zero'ing a register) is faster than a load immediate of a constant value.

    On the other hand, a good optimising compiler should be able to inspect the loop inner and determine that going backwards won't cause any side effects...

    BTW, that is a terrible interview question in my opinion. Unless you are talking about a loop which runs 10 millions of times AND you have ascertained that the slight gain is not outweighed by many instances of recreating the forward loop value (n - i), any performance gain will be minimal.

    As always, don't micro-optimise without performance benchmarking and at the expense of harder to understand code.

提交回复
热议问题