Pointless Optimization
The other day I needed to write a function to give me a formatted string representation of a quantity of bytes. Pretty trivial function, but nontheless, I found myself optimizing it. I ended up with the following:
static uint64_t count = 7;
static NSString *suffixes[7] =
{ @"B", @"KiB", @"MiB", @"GiB", @"TiB", @"PiB", @"EiB"};
uint64_t i, c;
for (i = 1024, c = 0; i < (count << 60); i <<= 10, c++) {
if (bytes < i)
return [NSString stringWithFormat: @"%0.2f%@",
(double)bytes / (double)(i >> 10),
suffixes[c]];
}
return @"Big";
Now, optimizing away divisions (except for the final conversion to string) really doesn't save any time at all. The creation and subsequent autorelease of a NSString will take far longer than the division operations, even for large byte counts. Thus, I believe this code sample qualifies as pointless optimization, although it was entertaining to write.
0 comments: