What is the fastest way to go through an array? I read a book about optimization in Javascript, it was said that the fastest way is this:

while(i--) { } 

I compared two ways: this and the usual cycle:

 for (var i = 1e7; i > 0; i = i - 1) {} 

It turned out that the usual cycle runs much faster, why? The forums also wrote that the way with while is the fastest.

I checked the speed of work like this:

 var i = 1e7; var t = performance.now(); while(i--) {} console.log(performance.now() - t); var t = performance.now(); for (var i = 1e7; i > 0; i = i - 1) {} console.log(performance.now() - t); 
  • one
    on empty cycles checked? :) in which browsers? - Grundy
  • I do not know, it gives me the first one, then the second one. And it's better to fill the loop body with something. - Dmitry Chistik
  • It seems to me that the normal optimizer should throw out both cycles. If with for it is generally obvious, then with while it is necessary to look, suddenly i used somewhere outside ... Maybe this is the case? - pavel
  • @Grundy; I didn’t write any calculations here. And so, I tested these methods on arrays, the second method still turned out to be faster. Checked in Chrome :) - Reaget
  • @ Rifat, it is worth checking the other browsers: FF, Safari, IE, EDGE. In any of them, the results can be different, besides, if we are talking about array processing, we should add cases of using Array methods to the test: forEach for example - Grundy

1 answer 1

The fastest is for, there are a lot of reviews and articles on this topic, for example, here , and there was a very good benchmark on jsperf.com , but now it is not working, maybe at the time of reading the answer it will already be available, this benchmark was good compared not just for vs foreach, but also different ways of implementing for. The book can be described theoretical point, all modern browsers optimize the code, and for them the behavior of for the most predictable, which means they speed it up much more efficiently.

  • in fact, the topic is interesting, although the site is not available, but you can find screenshots in Google, such as image.slidesharecdn.com ... , for example, such a time that the reverse for faster than the direct, for example, when I tested myself in chrome faster than direct, not much but interesting fact all the same - pnp2000