I think most programers have heard the famous Donald Knuth quote:
We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil
And it’s so easy to think that you wouldn’t do that, you’re a smart programmer. And for the big decisions we ask ourselves “is this premature optimization?” and we change our course accordingly.
However, it’s my assertion that we forget this phrase for the small decisions. We think we’re saving a bit of time, cutting a corner to grab some gain, while in reality, we’re prematurely optimizing.
And then, when you get a combination of these little optimizations, you’re stuck with a big case of premature optimization. In such a case the these optimizations are less obvious, because they’re small and there’s nothing glaringly obvious to track down.
I did this last week and would like to share why you should use Cocoa’s UIColor everytime.
My code looked like this:
+ (UIColor *)clearColor {
static UIColor * clearBackgroundColor = nil;
if (!clearBackgroundColor) {
clearBackgroundColor = [[UIColor clearColor] retain];
NSCParameterAssert(clearBackgroundColor);
}
return clearBackgroundColor;
}
A nice method to prevent clearBackgroundColor from getting created over and over again. Clever right? This code was sitting live in my iPhone app myDomains. I decided to test the code and see if it really was as clever as I thought:
UIColor *colorTest;
NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
for (int i=0; i < 1000; ++i) {
colorTest = [UIColor whiteColor];
}
NSLog(@"%f", [NSDate timeIntervalSinceReferenceDate] - start);
start = [NSDate timeIntervalSinceReferenceDate];
for (int i=0; i < 1000; ++i) {
colorTest = [Constants clearColor];
}
NSLog(@"%f", [NSDate timeIntervalSinceReferenceDate] - start);
I wrapped a normal call to UIColor and a call to my Uber-Awesome-Time-Saving-Color-Method with a for loop and a timer. The result?
UIColor = 0.000011 Me = 0.000190
That’s right, Apple’s code ran 17x faster than mine. Luckily I caught my optimization early, while the codebase was small and the correction was easy.
Really though, I should have known… I’m not smarter than Apple.