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?
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?
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:
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.
You are warned.