Last Updated: February 25, 2016
· francesco
995874 10203292335448877 1165866291 n

Javascript performance optimization: profiling

To profile Javascript performance, the typical code would be something like this:

var start = new Date().getTime();
/* [code to be profiled] */
var time = new Date().getTime() - start;

But, when the code that need to be profiled by the various browsers executes in a few milliseconds, it's better to run the test various times to be able to perform a sort of statistic mean.

Instead of measure the time of one iteration, it is more accurate to track how many iteration occurs in a certain amount of time (in the example below, 1000ms):

var iterations = 0;
var start = new Date().getTime();
for (var iterations=0; time<1000; iterations++) {
    /* [code to be profiled] */
    time = new Date.getTime() - start;

The for cycles until time is below 1000ms, then exits revealing how many iterations have occurred.

Say Thanks

4 Responses
Add your response


Worth adding that Chrome and (supposedly Firefox 15+ and IE 10+) also support Hight Resolution Timer via (or performance.webkitNow() in older versions). You should use it whenever possible.

More info on

over 1 year ago ·
995874 10203292335448877 1165866291 n

Thanks Dmitry, interesting!

over 1 year ago ·

Problem with test-loops like this is: Engines like v8 optimize more and more over time(wich is why it's so great for server-side scripts) but you probably won't get those effects on a regular website or webapp, because most of the code runs like once or twice but rarely thousands of times(unless you do things like some UI effects, etc.)

Also modern browsers tend to bring performance testing tools with them - e.g. Chrome has different tools for JS, CSS and memory profiling.

over 1 year ago ·
995874 10203292335448877 1165866291 n

Yep, absolutely, and it's a really good thing that web development is finally being supported consistently.

There's also services like that evaluate script performances...

over 1 year ago ·