Testing JavaScript performance

Technology is constantly evolving. We might not be pushing the boundaries of our browsers right now but you never know when JavaScript performance might be important. This article will show you two code samples that you can use to measure your JavaScript’s performance.

Modern browsers

If you’re using a modern browser you can take advantage of the performance object. It’s a built in object that lets you easily track the amount of time in milliseconds with floating point precision from when it’s called.

Performance object example

var start = performance.now();
var sum = 0;

for (var x = 0; x < 10000; x++) {
    sum = sum + x;
}

var end = performance.now();

console.log("Time: " + (end - start));

Browser compatibility

Browser Version
Internet Explorer 10
Chrome 20
Firefox 15
Opera 15
Safari Not supported

Visit Mozilla's developer network site for more information.

Older browsers

There's an alternative to the performance object if you're not able to use a browser that supports it. In this section I'll show you how you can track your JavaScript performance using the date object. The date object is supported in all browsers so there's no need to worry about browser compatibility with this technique.

Date object example

var start = new Date().getTime();
var sum = 0;

for (var x = 0; x < 10000; x++) {
    sum = sum + x;
}

var end = new Date().getTime();

console.log("Time: " + (end - start));