Hacker News new | ask | show | jobs
by dmccarty 990 days ago
Processors are inherently awesome at branching, adding, adding, shifting, etc. And shifting to get powers of 2 (i.e., KB vs. GB) is a superpower of its own. They're a little less awesome when it comes to math.pow(), math.log(), and math.log() / math.log().

Why 300K+ people copied this in the first place shows some basic level of ignorance about what's happening under the hood.[1]

As someone who's been at this for decades now and knows my own failings better than ever, it also shows how developers can be too attracted by shiny things (ooh look, you can solve it with logs instead, how clever!) at the expense of readable, maintainable code.

[1] But hey, maybe that's why we were all on StackOverflow in the first place

1 comments

> Processors are inherently awesome at branching, adding, adding, shifting, etc. And shifting to get powers of 2 (i.e., KB vs. GB) is a superpower of its own. They're a little less awesome when it comes to math.pow(), math.log(), and math.log() / math.log().

And here's something to consider -- if you're converting a number to human readable format it's more likely than not your about to do I/O with the resulting string, which is probably going to be an order of magnitude more expensive than the little function here.

Great point, I wish I'd mentioned it. The expense of the printf dwarfs the log / log (double divided by a double then cast to an int), which itself is greater than some repeated comparisons in a for loop.

It's key to be able to recognize this when thinking about performant code.

In other words, the entire exercise is silliness because the eventual printf is going to blow away any nanoseconds of savings by a smarter/shorter routine.