While vs Do While vs For (v5)

Revision 5 of this benchmark created by Andy on


Description

Also be careful when you use pre- and postdecrement with while or do-while, with do-while and while loops, there'll be differences!

If you know how many runs you have, you should always use a for-loop. Not only because of the increase in perfomance, but because it's clearly indicating said case. Plus you don't have any counting variables left which you could reuse by accident with wrong numbers. Also post- or predecrement/-increment doesn't make a difference which could easily yield a off-by-one-bug if you use a while or do-while.

Test runner

Ready to run.

Testing in
TestOps/sec
While loop
var i = 10000;
while (i--) {
  Math.cos(Math.PI);
}
ready
Do-While loop
var i = 10000;
do {
  Math.cos(Math.PI);
} while (--i);
ready
For loop (decrementing)
for (var i = 10000; i > 0; i--) {
  Math.cos(Math.PI);
}
ready
For loop (decrementing)
for (var i = 10000; i > 0; --i) {
  Math.cos(Math.PI);
}
ready
For loop (incrementing)
for (var i = 0; i < 10000; i++) {
  Math.cos(Math.PI);
}
ready
For loop (incrementing)
for (var i = 0; i < 10000; ++i) {
  Math.cos(Math.PI);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.