A lot of things have been said over the years about premature optimization, and after running into the following bug I thought it served as a good example of a type of premature optimization that I call “micro-optimization”. That is, doing something quirky in order to save a tiny amount of RAM or CPU cycles. More often than not these quirks lead to bugs and less maintainable code, with no actual performance increase.
The following bug was in a class in an application designed to run on a modern desktop, and there would only be a few instances alive at any one time (say, 1-10 typically, maybe 100 in edge cases), so the amount of memory saved was negligible (if any).
This is a rather easy “spot the bug” exercise so I won’t give it away. 😉
DWORD WEATHER_SUNNY = 0x0001;
DWORD WEATHER_RAINING = 0x0002;
_fRaining = (dwFlags & WEATHER_RAINING);
cout << “It’s raining!” << endl;
cout << “It’s not raining!” << endl;
Note: Depending on your compiler, if you crank up your warning level high enough you should get a warning for this. (Although curiously I didn’t with VS 2005 and /W4).