Javascript中位运算的效率

Efficiency of bitwise operation in Javascript

根据w3schools

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

所以我的问题来了:如果我们要执行按位运算,javascript如何将 64 位 IEEE 754 标准浮点数转换为普通的 32 位整数,效率如何?从直觉上看,转换数字的成本很高,所以使用位移比乘以 2n 是否更有效?

非常感谢!

来自好的部分

Bitwise operators work with integers. JavaScript doesn't have integers. It only has double precision floating-point numbers. So, the bitwise operators convert their number operands into integers, do their business, and then convert them back. In most languages, these operators are very close to the hardware and very fast. In JavaScript, they are very far from the hardware and very slow.

不过,最终,行为几乎总是特定于实现的。一些 JavaScript 环境可能 - 今天或将来 - 能够推断这段或那段代码将始终像 int 一样处理,或者默认情况下将 vars 存储为 ints。

唯一确定的方法是分析您的代码。像 JSPerf 这样的工具可能会有帮助。它也可能给你矛盾的指标——在一个浏览器中运行得更快的东西在另一个 JavaScript 引擎中可能表现不佳。性能提升还可能取决于您自己的生产代码在不知不觉中破坏的试探法。

不过,真正的问题是另一个问题:您打算做什么才能使乘法性能成为性能的关键因素?因为这可能不是您应该在 UI 阻塞客户端脚本中执行的操作。