问题描述
我见过一些对性能至关重要的 javascript 代码,例如 这个项目 上的代码使用与 0 的按位或运算.例如:
I've seen some performance critical javascript code, like the one on this project that makes extensive use of bitwise OR operations with 0. Ex:
GameBoyAdvanceCPU.prototype.write8 = function (address, data) {
address = address | 0;
data = data | 0;
this.memory.memoryWrite8(address | 0, data | 0);
我知道带有|0"的楼层编号的用例,但这里的情况并非如此,因为这些总是整数.它看起来有点像asm.js,这是告诉js引擎我们正在处理整数,允许一些优化吗?如果是这样,哪些浏览器会进行这些优化?
I know about the use case of flooring numbers with "|0", but that isn't the case here, as these are always int's. It looks a bit like asm.js, is this to tell the js engine that we are working with integers, allowing some optimizations? If so, which browsers will make those optimizations?
任何有关其工作原理的指示都将被赞赏.
Any pointers to how this works would be appretiated.
推荐答案
在()中包装整数算术表达式|0
允许运行时确保您正在执行整数算术而不是浮点算术.这使它在许多情况下可以避免检查溢出并生成更快的代码.
并且根据该页面,大多数"Javascript 运行时都是如此,但没有说明是哪个.
and according to the page, it's true for "most" Javascript runtimes, but doesn't say which.
作为第二个来源,为游戏和游戏编写快速 JavaScript交互式应用程序 状态
As a second source, Writing Fast JavaScript For Games & Interactive Applications states
要告诉 JavaScript 引擎我们想要存储整数值 [...] 我们可以使用按位或运算符:
以及来自 微软编写高效 JavaScript 页面的第三个来源:
[...] 明确告诉 JavaScript 运行时使用整数算法 [...] 使用按位或运算符
此外,除了评论之外,上面的页面都没有提到 asm.js,所以我怀疑此类优化适用于未明确标记为 asm/在未明确识别的浏览器中的代码.
这篇关于这是什么 asm 样式 "x |0"一些 javascript 程序员现在正在使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!