Hacker News new | ask | show | jobs
by shurcooL 3394 days ago
You have to keep in mind that adding support for special cases makes the general case a little bit slower (because it has to always check if it's the special case or not). It's not completely free to make pow work fast on small integers.

So, it's a trade-off. I would also prefer less special cases optimized for naive use, but only if it's accompanied by documentation that says "prefer X instead of pow(x, 2), prefer Y instead of pow(-1, k), etc." It shouldn't be guesswork as to what's best to do for common cases.

2 comments

That's not necessarily true. I'd wager that most cases where pow(x, 2) is used as a way to square x, the "2" is actually a constant. That's trivially statically optimizable at compile time.
In fact, if you are using pow specifically to "square a number" in the sense where you could replace it with x*x, it is guaranteed to be something you can determine statically (and probably pretty easily) - or you're already doing a lot of unnecessary work.
Most of the time, you can opt out of these optimizations.