Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

I've been working on web based projects built mainly with PHP and JavaScript, where I mostly use Zend Framework and jQuery. I am interested in any webpage optimizations techniques - for a faster web! Stoimen is a DZone MVB and is not an employee of DZone and has posted 52 posts at DZone. View Full User Profile

JavaScript Performance: for vs. while

January 27, 2012 AT 1:16 AM
  • submit to reddit

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!

 for vs. while

JavaScript Performance: for vs. while

 

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

Comments

Anita Dande replied on Sat, 2012/01/28 - 9:42pm

ohoo this is execellent, thanks for shairing.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.