logoalt Hacker News

bugake • today at 2:44 AM • 3 replies • view on HN

For the uninformed: counting backwards in a for loop is faster because comparing an unsigned integer against 0 is generally faster than comparing it against any other value.

It also says not to use `for (i >= 0)` because any unsigned integer is >= 0, and the loop will never end.


Replies

StilesCrisis • today at 3:50 AM

Optimizers eat stuff like this up. It'll restructure your loop however it wants.

➕ show 1 reply
flohofwoe • today at 7:40 AM

> ...counting backwards in a for loop is faster...

Maybe in 1990 ;)

(it's one of many cargo cult wisdom snippets that have become mostly obsolete once C compilers got proper optimizer passes and CPUs got all sorts of pipeling tricks)

sltkr • today at 3:38 AM

> For the uninformed: counting backwards in a for loop is faster because comparing an unsigned integer against 0 is generally faster than comparing it against any other value.

No it's not. It generally makes no difference at all.

If you disagree, I dare you to write a benchmark that demonstrates a difference between forward and backward iteration on a modern CPU.

➕ show 2 replies