1

I saw this problem from some blog. The following two loops are given, the question is which one is faster.

for(int i = 100000; i > 0; i--) {}
for(int i = 1; i < 100001; i++) {}

Why the first one is faster than the second one?

Ryan
  • 2,825
  • 9
  • 36
  • 58

1 Answers1

6

On some processors in code generated by some compilers the first one could be faster because the value is compared to zero. As @DeadMG notes it applies, for example, to x86 processors before 1985.

But it is:

  • a premature optimization, don't change first line to the second only because of this reason! Donald Knuth once said and I totally agree with him

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

  • a non-portable optimization - it works faster only on some specific processors in some specific cases! And with a high probability it will work not just the same but even slower on other architectures.

You are warned.

sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
  • 1
    To be more specific, this has only been the case on, for example, x86 processors before 1985. So you might want to be a lot more specific about what processors you think this applies to. – Puppy Jul 28 '13 at 22:14
  • And it's a carry over from C, where you can code the condition as simply `i`, ie `for(int i = 100000; i; i--)` – Bohemian Jul 29 '13 at 00:01