Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JavaScript Performance: for vs. while

DZone's Guide to

JavaScript Performance: for vs. while

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

If you have read some preformance tests on JavaScript loops, you may have heard that “while” is faster than “for”. However the question is how faster is “while”? Here are some results, but first let’s take a look on the JavaScript code.

The for experiment

console.time('for');
for (var i = 0; i < 10000000; i++) {
	i / 2;
}
console.timeEnd('for');

The while experiment

console.time('while');
var i = 0;
while (i++ < 10000000) {
	i / 2;
}
console.timeEnd('while');

Note – these tests are performed and measured with Firebug on Firefox.

Results

It’s a fact, that you’ll get different results as many times as you run this snippet. It depends also on the enviroment and software/hardware specs. That is why I performed them 10 times and then I took the average value. Here are the values of my performance tests. Note that both for and while perform 10,000,000 iterations.

And the Winner Is

While is the winner with an average result of 83.5 milliseconds, while “for” result is 88 average milliseconds.

As the diagram bellow shows, the while loop is slightly faster. However we should be aware that these performance gains are significant for large number of iterations!

JavaScript Performance: for vs. while

JavaScript Performance: for vs. while

 

From http://www.stoimen.com/blog/2012/01/24/javascript-performance-for-vs-while

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}