javascript - 某些 javascript 程序员现在使用的 asm 样式 "x | 0"是什么?

标签 javascript optimization bit-manipulation vm-implementation asm.js

我见过一些性能关键的 javascript 代码,比如 this project 上的代码广泛使用与 0 的按位或运算。例如:

GameBoyAdvanceCPU.prototype.write8 = function (address, data) {
address = address | 0;
data = data | 0;
this.memory.memoryWrite8(address | 0, data | 0);

我知道带“|0”的底数的用例,但这里不是这种情况,因为它们始终是整数。它看起来有点像 asm.js,这是告诉 js 引擎我们正在处理整数,允许进行一些优化吗?如果是这样,哪些浏览器会进行这些优化?

任何有关其工作原理的指示都将受到赞赏。

最佳答案

根据 JavaScript Performance for Madmen

Wrapping integer arithmetic expressions in ( ) | 0 allows the runtime to be sure that you're doing integer arithmetic instead of floating-point arithmetic. This allows it to avoid checking for overflow and produce faster code in many cases.

并且根据该页面,“大多数”Javascript 运行时都是如此,但没有说明是哪个。

作为第二个来源,Writing Fast JavaScript For Games & Interactive Applications

To tell JavaScript engine we want to store integer values [...] we could use bitwise or operator:

第三个来源来自Microsoft's Writing efficient JavaScript page :

[...] explicitly tell the JavaScript runtime to use integer arithmetic [...] use the bitwise or operator

另外,除了评论之外,上面的页面都没有提到 asm.js,因此我怀疑此类优化适用于未明确标记为 asm 的代码/在未明确识别它的浏览器中。

关于javascript - 某些 javascript 程序员现在使用的 asm 样式 "x | 0"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156122/

相关文章:

C++ const引用参数优化

c++ - 有没有一种简单的方法来获得 std::bitset<N> 的 2 的补码

sql - 我可以将一堆 boolean 列转换为 PostgreSQL 中的单个位图吗?

php - 将 "password is ok"存储在 php session 变量中?

javascript - JQuery 游戏 - 让玩家在 % 值中平滑移动

javascript - 什么样的CSS3动画是异步的?

optimization - genStrAsCharArray 优化的好处

c++ - 关于尾递归优化

c++ - 按位操作或按位编程

javascript - jquery去除循环动画