Hacker News new | ask | show | jobs
by coroutines 3710 days ago
I think it's important to remember that Array::map() and Array::filter() construct new Arrays (even if the old one is quickly "lost" and collected). It's probable v8 sees this and does some trickery to make use of the existing allocated Array, but I doubt it.

let next = [ 1, 2, 3, 4 ].map(x => x * 2);

versus:

next = (x * 2 for x in [ 1 .. 4 ])

...which becomes:

// Generated by CoffeeScript 1.10.0

(function() { var next, x;

  next = (function() {
    var i, results;
    results = [];
    for (x = i = 1; i <= 4; x = ++i) {
      results.push(x * 2);
    }
    return results;
  })();
}).call(this);

Array::map()/filter() get points for encouraging immutable transformations.

1 comments

This could probably be solved if Javascript had map/filter/reduce functions for iterators (and hopefully dictionaries) as well as arrays.

And of course a range(start,stop,step) iterator similar to python's range.

it would then be a matter of:

  next = range(1,40000).map(x => x * 2);
and because range would be an iterator, the only array created would be next.