我想知道是否有可能了解V8到底是如何优化和内联的。
我创建了三个简单的test functions,它们都以度为单位计算角度的正弦。我将它们都放入闭包中,以便V8能够内联本地变量。
使用预先计算的常量
Math.PI / 180
,然后执行Math.sin(x * constant)
.我使用了以下代码:
var test1 = (function() {
var constant = Math.PI / 180; // only calculate the constant once
return function(x) {
return Math.sin(x * constant);
};
})();
var test2 = (function() {
var pi = Math.PI; // so that the compiler knows pi cannot change
// and it can inline it (Math.PI could change
// at any time, but pi cannot)
return function(x) {
return Math.sin(x * pi / 180);
};
})();
var test3 = (function() {
return function(x) {
return Math.sin(x * 3.141592653589793 / 180);
};
})();
令人惊讶的是,结果如下:
test1 - 25,090,305 ops/sec
test2 - 16,919,787 ops/sec
test3 - 16,919,787 ops/sec
看起来pi
确实在test2
中被内联,因为test2
和test3
导致的每秒操作量完全相同。
另一方面,除法似乎没有得到优化(即预先计算),因为test1
的速度要快得多。
https://stackoverflow.com/questions/8029106
复制相似问题