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;
}
alert(iterations);
The for cycles until time is below 1000ms, then exits revealing how many iterations have occurred.
Written by Francesco Zaia
Related protips
4 Responses
Worth adding that Chrome and (supposedly Firefox 15+ and IE 10+) also support Hight Resolution Timer via performance.now()
(or performance.webkitNow()
in older versions). You should use it whenever possible.
Thanks Dmitry, interesting!
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.
Yep, absolutely, and it's a really good thing that web development is finally being supported consistently.
There's also services like http://jsperf.com/ that evaluate script performances...