logoalt Hacker News

bugake • today at 5:50 AM • 1 reply • view on HN

I quote from "Optimizing Software in C++" by Agner Fog:

"Comparing an integer to zero is sometimes more efficient than comparing it to any other number. Therefore, it is slightly more efficient to make a loop count down to zero than to make it count up to some positive value, n. But not if the loop counter is used as an array index. The data cache is optimized for accessing arrays forwards, not backwards."

Yet that text was written for older CPUs. Modern CPUs are better at prefetching backwards access patterns, but if you try a microbenchmark with backwards array traversal, you may get misleading results.


Replies

StilesCrisis • today at 11:41 AM

Agner Fog is also discussing CPU architecture, not high-level language. The whole point is that the optimizer _already_ takes knows these things and rewrites your code automatically. If you write a zero-to-100 loop in C, that doesn’t mean the assembly will literally show a value going from zero to 100; it may unroll, or reverse the loop order, or any weird combination of things that the optimizer has decided will be equivalent and fast.