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

倾然丶 夕夏残阳落幕 提交于 2019-12-23 12:16:49

问题


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 vs while 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!