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

In these tests, http://jsperf.com/the-loops Barbara Cassani showed that the "back at the time" cycle is faster,

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

than a regular for loop:

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

Why?

Update

Well, forget about it, there is an error in the test, iterations = 100 , it is executed only once per page. Therefore, its reduction, well, that means that we really do not go into loops. Unfortunately.

+4
source share
2 answers

This is due to the nature of the internal components of each JavaScript engine. Do not use it for optimization, because you cannot logically rely on it, always faster when the engines change. For example, check out the latest version of the test that you linked , and note that the difference is much less if it exists at all in recent browsers.

+1
source

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

  • for vs while doesn't matter
  • but > or < better than !==

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

+1
source

Source: https://habr.com/ru/post/1415546/


All Articles