Why is Javascript's Math.floor the slowest way to calculate floor in Javascript?

javascript, optimization

Solution

It has nothing to do with modern browsers. It has to do with implementing the ECMA standard. You can't just change how a certain function performs even if there is a faster way. It could break existing code.

The Math.Floor has to account for a lot of different scenarios of handling different types. Could they have made different scenarios faster by taking short cuts as you described? Maybe they could, but that might have broken other scenarios. Just because something on the surface looks small, doesn't mean that there isn't an iceberg underneath.

Problem

I'm generally not a fan of microbenchmarks. But this one has a very interesting result. http://ernestdelgado.com/archive/benchmark-on-the-floor/ It suggests that `Math.floor` is the SLOWEST way to calculate floor in Javascript. `~~n`, `n|n`, `n&n` all being faster. This seems pretty shocking as I would expect that people implementing Javascript in today's modern browsers would be some pretty smart people. Does floor do something important that the other methods fail to do? Is there any reason to use it?

Original source