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.
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
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');
(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).
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With