Fastest loop in Javascript

As of June 2016, doing some tests in latest Chrome (71% of the browser market in May 2016, and increasing):
  • The fastest loop is a for loop, both with and without caching length delivering really similar performance. (The for loop with cached length sometimes delivered better results than the one without caching, but the difference is almost negligible, which means the engine might be already optimized to favor the standard and probably most straightforward for loop without caching).
  • The while loop with decrements was approximately 1.5 times slower than the for loop.
  • A loop using a callback function (like the standard forEach), was approximately 10 times slower than the for loop.
I believe this thread is too old and it is misleading programmers to think they need to cache length, or use reverse traversing whiles with decrements to achieve better performance, writing code that is less legible and more prone to errors than a simple straightforward for loop. Therefore, I recommend:
  • If your app iterates over a lot of items or your loop code is inside a function that is used often, a straightforward for loop is the answer:
    for (var i = 0; i < arr.length; i++) {
      // Do stuff with arr[i] or i
  • If your app doesn't really iterate through lots of items or you just need to do small iterations here and there, using the standard forEach callback or any similar function from your JS library of choice might be more understandable and less prone to errors, since index variable scope is closed and you don't need to use brackets, accessing the array value directly:
    arr.forEach(function(value, index) {
      // Do stuff with value or index
  • If you really need to scratch a few milliseconds while iterating over billions of rows and the length of your array doesn't change through the process, you might consider caching the length in your for loop. Although I think this is really not necessary nowadays:
    for (var i = 0, len = arr.length; i < len; i++) {
      // Do stuff with arr[i]


Popular posts from this blog

MATLAB code for Circular Convolution using Matrix method

Positive number pipe in angular 2+