Hi, I ran into this question when i was answering another guys question. How do compilers optimize the code? Can keywords like const, ... help? Beside the fact with volatiles and inline functions and how to optimize the code all by your self!
One very big thing you can do ( beyond what the compiler can do for you ) is to be aware of the cache. Since accessing the memory is really time expensive, the cache tries to help you by storing not only the data you accessed it but the nearby elements as well. This is why foo
will run so much faster than bar
:
array[ NUM_ROWS ][ NUM_COLS ];
foo()
{
int row, col;
int sum = 0;
// accesses the elements in the array continuously
for ( row = 0; row < NUM_ROWS ; row++ )
{
for ( col = 0; col < NUM_COLS; col++ )
{
sum += array[ row ][ col ];
}
}
}
bar()
{
int row, col;
int sum = 0;
// skips from row to row ( big jumps that might miss the cache )
for ( col = 0; col < NUM_COLS ; col++ )
{
for ( row = 0; row < NUM_ROWS; row++ )
{
sum += array[ row ][ col ];
}
}
}
Edit:
Another thing to be aware of is repeated string concatenation. Done wrong, this can make code that otherwise seems to run in O( n )
actually be in O( n^2 )
- see an article on Joel on Software
Edit: s/disk/memory/
The rules of optimization:
- Don't do it
- Advanced Users Only: Don't do it yet
Edit: The quote (and other information, useful or not) can be found in the CodingHorror article: Hardware is cheap, programmers are expensive. It would be nice to find the 'origin' of this phrase/quote though.
Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed.
I would suggestion starting at the Compiler optimization wikipedia page as there are many different kinds of optimization that are performed at many different stages.
As you can see, modern compilers are very 'smart' at optimizing code (compiled C code is often faster than hand-written assembly unless the programmer really knows how to take advantage of all the specific processor instructions and quirks). As others have said, write for clarity first based on a good design.