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

前端 未结 2 908
醉话见心
醉话见心 2020-12-05 05:00

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 t

相关标签:
2条回答
  • 2020-12-05 05:25

    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.

    0 讨论(0)
  • 2020-12-05 05:25

    The primary reason Math.floor is slower (where it actually is--in some tests I've done it's faster) is that it involves a function call. Older JavaScript implementations couldn't inline function calls. Newer engines can inline the call, or at least make the property lookup faster, but they still need a guard condition in case you (or some other script) overwrote the Math.floor function. The overhead is minimal though, so there's not much difference in speed.

    More importantly though, as was mentioned in several comments, the other methods are not equivalent. They all work by doing bitwise operations. The bitwise operators automatically convert their operands to 32-bit integers by truncating the number. That's fine if the number fits in 32 bits, but JavaScript numbers are 64-bit floats, which could be much larger than 2147483647.

    They also give a different result for negative numbers, since converting to integers truncates and Math.floor always rounds down. For example, Math.floor(-2.1) === -3, but (-2.1) | (-2.1) === -2.

    If you know you are only dealing with positive numbers less than 2147483648, and you need to squeeze every bit of performance out of your code in older browsers (Make sure it's actually the bottleneck first. It probably isn't.), I would use an even simpler method: x|0. It doesn't evaluate the variable twice, and it works even if x is an expression (just be sure to put it in parentheses so you don't run into precedence issues).

    0 讨论(0)
提交回复
热议问题