re: Don’t pay the for-loop tax VIEW POST

VIEW FULL DISCUSSION
 

This expands the array and may cause it to reallocate in memory being slow

That's surely correct, but if you're interested in performance you should definitely use a for loop, as any solution based on callbacks, while more expressive, is one or two orders of magnitude slower, for small and large arrays:

console.time("Array.push");
var array = [];
for (var i = 0; i < 1e7; i++) array[i] = i;
console.timeEnd("Array.push");
// Array.push: 220ms

console.time("new Array.push");
var array = new Array(1e7);
for (var i = 0; i < 1e7; i++) array[i] = i;
console.timeEnd("new Array.push");
// new Array.push: 47ms

console.time("Array.map");
var array = [ ...Array(1e7).keys() ].map((_, i) => i);
console.timeEnd("Array.map");
// Array.map: 1209ms

But let's not forget that we also have for...in and, above all, for...of in JavaScript, which bring much nicer semantics.

These are my main cases of why I use for loops in JavaScript:

  1. I'm releasing an open source package which could be used in performance-intensive tasks;
  2. my code needs to be transpiled and things like for...of are polyfilled with an unbearable amount of code (in the case Babel can't infer if the collection is actually an array or any other kind of iterable);
  3. because - ah, screw it - it's clear enough since it's a pattern everyone knows, while building an array with [ ...Array(n).keys() ].map(...) is quite obscure at the first glance.

The rest of the article is pretty much spot-on. Concepts that need to be reiterated.

 

A little late to the discussion, but generating the array declaratively would probably go a little faster if we make Array think it's converting an "array-like" structure and provide a map function.

console.time("Array.from");
var array = Array.from({length: 1e7}, (_, i) => i);
console.timeEnd("Array.from");
 

Thank you for your insightful response. I totally agree that in performance-critical applications loops are the way to go and that the for...of loops addresses some of the problems I have with simple for loop.

I just believe it is easier to get it right with map/reduce. It fits in the "Make it run, make it right, make it fast, make it small" workflow nicely.

 

It's not just a little faster to use the for loop - it's orders of magnitude faster. Why adopt an abstraction that reduces performance of a code segment by upwards of 80% (tested 86% slower on my desktop, 84% slower on iPad gen 5).

Like why adopt inefficient design patterns in the first place?

jsperf.com/old-man-yells-at-clouds...

code of conduct - report abuse