我目前正在编写一个小框架来测试 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