如何比较两个Javascript函数的速度?

时间:2012-02-17 17:20:15

标签: javascript jquery performance

我有一些正在阅读某些XML的Javascript。有一个较旧的函数用于从该数据创建一个JSON对象,我编写了一个新函数,希望能更快地创建该JSON对象。 确定哪个函数执行速度更快的最简单,最好的方法是什么?这是一个相当数量的数据,所以知道它有点重要。 感谢。

6 个答案:

答案 0 :(得分:12)

您可以使用console.time("ID");console.timeEnd("ID");(信息here),然后在Chrome开发者工具或Firebug中查看结果,如下所示:

console.time("oldFunc");
//oldfunc();
console.timeEnd("oldFunc");

console.time("newfunc");
//newfunc();
console.timeEnd("newfunc");

另外,您可以使用jsperf

答案 1 :(得分:2)

(new Date).getTime();

这是以毫秒为单位获取当前时间的方法。在执行代码之前和之后执行此操作,减去并且您有几毫秒的执行时间。

样品:

var start=(new Date).getTime();
//call your code
alert('Code took '+((new Date).getTime()-start)+'ms');

如果您的代码组织允许,您可以在for循环中进行调用,重复n(比如说1000次)并在最后将时间除以n。

通过这种方式,您可以获得平均速度,如果您的功能变化很大(如网络呼叫),这将特别有用。

答案 2 :(得分:1)

我喜欢测试函数性能的John Resigs way

function runTest(name, test, next){
  var runs = [], r = 0;
  setTimeout(function(){
    var start = Date.now(), diff = 0;

    for ( var n = 0; diff < 1000; n++ ) {
      test();
      diff = Date.now() - start;
    }

    runs.push( n );

    if ( r++ < 4 )
      setTimeout( arguments.callee, 0 );
    else {
      done(name, runs);
      if ( next )
        setTimeout( next, 0 );
    }
  }, 0);
}

答案 3 :(得分:1)

此处的一些信息和此处的代码示例

http://www.einternals.com/blog/web-development/javascript-find-script-execution-time-2

var startDate = new Date(); 

// execute your tasks here

var endDate = new Date();

var timeTaken = endDate.getTime() - startDate.getTime();

alert('Time take to execute the script is '+timeTaken+' milliseconds');

答案 4 :(得分:0)

这是在浏览器还是服务器端?

如果它是服务器端,我建议使用你选择的shell脚本工具进行基准测试(linux有time,windows有......无论窗口有什么)。

如果它在浏览器中,那么你总是可以包装一定数量的迭代(10,000通常就足够了):

var start = new Date.getTime();

var runs = 10000;

while (runs) {
    // do stuff here

    runs--;
}

console.log('Finished in ' + (new Date.getTime() - start) + ' ms.');

答案 5 :(得分:0)

 var d1 = new Date();     
 function1();
 var d2 = new Date();
 console.log("Function 1 : ", d2.getTime() - d1.getTime());

 function2();
 var d3 = new Date();
 console.log("Function 2 : ", d3.getTime() - d2.getTime());