Which of these pieces of code is faster in Java?

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

    The loops are identical, except for one critical part:

    i > 0; and i < 100001;

    The greater than zero check is done by checking the NZP (Commonly known as condition code or Negative Zero or Positive bit) bit of the computer.

    The NZP bit is set whenever operation such as load, AND, addition ect. are performed.

    The greater than check cannot directly utilize this bit (and therefore takes a bit longer...) The general solution is to make one of the values negative (by doing a bitwise NOT and then adding 1) and then adding it to the compared value. If the result is zero, then they're equal. Positive, then the second value (not the neg) is greater. Negative, then the first value (neg) is greater. This check takes a slightly longer than the direct nzp check.

    I'm not 100% certain that this is the reason behind it though, but it seems like a possible reason...

提交回复
热议问题