Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare the speed of two Javascript functions?

I have some Javascript that is reading in some XML. There is an older function which was used to create a JSON object from that data, and I've written a new function that I hope will create that JSON object faster. What is the easiest and best way to determine which function is performing faster? It's a decent amount of data, so it's somewhat important to know. Thanks.

like image 872
Munzilla Avatar asked Feb 17 '12 17:02

Munzilla


4 Answers

You could use console.time("ID"); and console.timeEnd("ID"); (info here), and look the results in the Chrome Developer Tools or Firebug like so:

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

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

Also, you could use jsperf

like image 147
nicosantangelo Avatar answered Sep 28 '22 01:09

nicosantangelo


Some info on this and code sample here

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');
like image 35
kiranvj Avatar answered Sep 28 '22 00:09

kiranvj


(new Date).getTime();

This is how you get current time in milliseconds. Do that before and after execution of code, subtract and you have execution time in miliseconds.

Sample:

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

If your code organisation allows, you can make your call in a for loop, repeating n (let's say 1000) times and divide the time by n at the end.

This way you get the average speed, which is especially helpful if you function varies a lot (like network calls).

like image 22
Rok Kralj Avatar answered Sep 28 '22 01:09

Rok Kralj


I like John Resigs way of testing the performance of a function:

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);
}
like image 40
fb55 Avatar answered Sep 28 '22 01:09

fb55