Pages

Friday, January 8, 2010

Slim your loops

The most common way to write for loops in C++ would probably be

for (int i = 0; i < size(); i++)

Since size() is a function call here one may want to store the value of size() in a variable before entering the loop. If the iteration order is not important you can do it this way

for (int i = size() - 1; i >= 0; i--)

This however look less clean and is longer to write. Now there is an old less common variant of the above line which does exactly the same

for (int i = size(); i--;)

Faster to write and the compiler outputs less assembly code. So this would actually be faster to write and execute faster, in raw execution cycles that is. It might affect the data cache in a negative way on non-x86 platforms, maybe I should check that before posting.

No comments:

Post a Comment