我目前正在编写一个小框架来测试JavaScript函数的速度。当我用相同的参数反复调用相同的方法时,它给我带来了奇怪的结果:
Function Execution Time
isEvenBitwise 38.00000000046566
isEvenModulo 38.00000000046566
isEvenPointless 38.00000000046566
以下是我的功能:
var myFunctions =
{
isEvenBitwise: function(number)
{
return !(number & 1);
},
isEvenModulo: function(number)
{
return (number % 2 == 0);
},
isEvenPointless: function(number)
{
return 1;
}
}
运行函数的代码:
PerformanceTest.prototype.measureTime = function()
{
for (var indexTests = 0; indexTests < this.testCount; indexTests++)
{
var results = [];
for (var currentFunction in this.functions) {
var contextFunction = this.functions[currentFunction];
var startTime = performance.now();
for (var i = 0; i < this.iterationsPerTest; i++)
{
var heh = contextFunction.apply(this, arguments)
}
var executionTime = performance.now() - startTime;
var result = {};
result.testName = currentFunction;
result.executionTime = executionTime;
results.push(result);
}
this.testResults.push(results);
}
}
JavaScript解释器是否缓存/优化我的代码?如果是这样,它是如何工作的?或者还有其他事情我不知道吗?
编辑:这似乎只发生在chrome中,firefox可以正常使用这些结果:
Function Execution Time
isEvenBitwise 9.652258097220447
isEvenModulo 37.546061799704376
isEvenPointless 8.512472488871936
答案 0 :(得分:0)
在查看您的代码之后,我将猜测Chrome对您正在做的事情非常聪明。它看到了这个:
var startTime = performance.now();
for (var i = 0; i < this.iterationsPerTest; i++)
{
var heh = contextFunction.apply(this, arguments)
}
var executionTime = performance.now() - startTime;
正确地评估contextFunction没有副作用,认识到heh
变量仅存在于循环范围内并且从未使用过,然后优化整个循环,因为它没有做任何事情。