Marek
Marek

Reputation: 3509

In JavaScript, why is a "reverse while" loop an order of magnitude faster than "for"?

In these benchmarks, http://jsperf.com/the-loops, Barbara Cassani showed that a "reverse while" loop is way faster,

while (iterations > 0) {
    a = a + 1;
    a = a - 1;
    iterations--;
}

than a usual "for" loop:

for (i = 0; i < iterations; i++) {
    a = a + 1;
    a = a - 1;
}

Why?

Update

Okay, forget about it, there is a bug in the test, iterations = 100, is executed only once per page. Therefore reducing it, well, means that we don't really enter the loops. Sorry.

Upvotes: 4

Views: 2041

Answers (2)

Marek
Marek

Reputation: 3509

Except for the big bug in the initial test, here are the results:

  • for vs while makes no difference
  • but > or < are better than !==

http://jsperf.com/the-loops/15

Upvotes: 2

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22481

It is because of of specifics of internals of each JavaScript engine. Don't use it for optimization, because you can't logically count on it always be faster as engines change. For example, check out last revision of test you've linked and note that difference is much more smaller if exists at all on recent browsers.

Upvotes: 1

Related Questions