2

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

1 回答 1

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变量仅存在于循环范围内并且从未使用过,然后优化整个循环,因为它没有做任何事情。

于 2013-04-18T10:20:10.740 回答