问题
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.
回答1:
Except for the big bug in the initial test, here are the results:
for
vswhile
makes no difference- but
>
or<
are better than!==
http://jsperf.com/the-loops/15
回答2:
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.
来源:https://stackoverflow.com/questions/10848552/in-javascript-why-is-a-reverse-while-loop-an-order-of-magnitude-faster-than