Premature optimization · Jan 22, 12:53 AM
Every coder has heard of premature optimization; paying too much attention to details that might turn out to be unimportant in the scheme of things. “Don’t sweat the small stuff” to borrow a phrase from the self-help world.
If you’re working with GNU compilers though (gcc and g++) there’s one kind of optimization that it won’t hurt to try. I mean the one where the compiler does the work. Check the man page for the -O options (-O, -O1, -O2, -O3 and -Os) if you’re not aware of the differences.
By default, the compiler assumes you know what you are doing and write good code that will easily compile up. So, if you don’t ask for anything special it will just do a quick job of compiling the code. In the days when computers were slow and short of memory that was probably a good option.
These days, however, computers are faster and have more memory. That means that it makes sense to have the compiler take more care over the code that is produced. This is what the optimization options do. The compiler carefully considers what can be removed or reorganized to make the program do the same thing but faster or with fewer instructions (which usually amounts to the same thing).
Recently I took some code that wasn’t optimized at compilation time and changed it to -Os (optimize for size). The compiler managed to squeeze the code into 75% of the space it used to take up and the speed was slightly improved. But there was an unexpected benefit too.
Since the compiler looks harder at the code, it can find more mistakes. Because of this, more warnings are produced by the compilers when they are optimizing than when they run without options. To make the most of the warnings, use the flags -Wall and -Werror – they will make sure the compiler doesn’t let you ignore any warnings.
Things like bits of code that can’t be reached, or variables that aren’t always initialized before use can be spotted. Some of these bugs would be hard to find with testing and hard to debug if they happened in software once it was in a customer’s hands.
You can buy expensive static analysis tools to find similar problems, although there is a risk they produce so many warnings that the important ones are hard to pick out. I found that turning on optimization has highlighted some of the more interesting bugs that I could have found with other tools. But I did it for free with gcc. So the moral is: always compile with -Wall -Werror and -O something and it’s never too early in a project to start doing so.

