12

Help! I'm learning to love Javascript after programming in C# for quite a while but I'm stuck learning to love the iterable protocol!

Why did Javascript adopt a protocol that requires creating a new object for each iteration? Why have next() return a new object with properties done and value instead of adopting a protocol like C# IEnumerable and IEnumerator which allocates no object at the expense of requiring two calls (one to moveNext to see if the iteration is done, and a second to current to get the value)?

Are there under-the-hood optimizations that skip the allocation of the object return by next()? Hard to imagine given the iterable doesn't know how the object could be used once returned...

Generators don't seem to reuse the next object as illustrated below:

function* generator() {
  yield 0;
  yield 1;
}

var iterator = generator();
var result0 = iterator.next();
var result1 = iterator.next();

console.log(result0.value) // 0
console.log(result1.value) // 1

Hm, here's a clue (thanks to Bergi!):

We will answer one important question later (in Sect. 3.2): Why can iterators (optionally) return a value after the last element? That capability is the reason for elements being wrapped. Otherwise, iterators could simply return a publicly defined sentinel (stop value) after the last element.

And in Sect. 3.2 they discuss using Using generators as lightweight threads. Seems to say the reason for return an object from next is so that a value can be returned even when done is true! Whoa. Furthermore, generators can return values in addition to yield and yield*-ing values and a value generated by return ends up as in value when done is true!

And all this allows for pseudo-threading. And that feature, pseudo-threading, is worth allocating a new object for each time around the loop... Javascript. Always so unexpected!


Although, now that I think about it, allowing yield* to "return" a value to enable a pseudo-threading still doesn't justify returning an object. The IEnumerator protocol could be extended to return an object after moveNext() returns false -- just add a property hasCurrent to test after the iteration is complete that when true indicates current has a valid value...

And the compiler optimizations are non-trivial. This will result in quite wild variance in the performance of an iterator... doesn't that cause problems for library implementors?

All these points are raised in this thread discovered by the friendly SO community. Yet, those arguments didn't seem to hold the day.


However, regardless of returning an object or not, no one is going to be checking for a value after iteration is "complete", right? E.g. most everyone would think the following would log all values returned by an iterator:

function logIteratorValues(iterator) {
  var next;
  while(next = iterator.next(), !next.done)
    console.log(next.value)
}

Except it doesn't because even though done is false the iterator might still have returned another value. Consider:

function* generator() {
  yield 0;
  return 1;
}

var iterator = generator();
var result0 = iterator.next();
var result1 = iterator.next();

console.log(`${result0.value}, ${result0.done}`) // 0, false
console.log(`${result1.value}, ${result1.done}`) // 1, true

Is an iterator that returns a value after its "done" is really an iterator? What is the sound of one hand clapping? It just seems quite odd...


And here is in depth post on generators I enjoyed. Much time is spent controlling the flow of an application as opposed to iterating members of a collection.


Another possible explanation is that IEnumerable/IEnumerator requires two interfaces and three methods and the JS community preferred the simplicity of a single method. That way they wouldn't have to introduce the notion of groups of symbolic methods aka interfaces...

17
  • Can you link to the spec where it says that a new object needs to be returned? Commented Dec 22, 2018 at 10:10
  • You'll likely no get an answer about specific language design decision here, since the people who work on the spec are not here. You should reach out to them directly. Commented Dec 22, 2018 at 10:11
  • 1
    @Bergi: Actually, that only describes the behavior of built-in iterators. The protocol itself doesn't seem to require a new object in each iteration. Commented Dec 22, 2018 at 10:24
  • 1
    FWIW, here is an example that reuses the result object: jsfiddle.net/wp82n07o . The specification of the protocol doesn't seem to require that a different object is returned in each iteration (as far as I can see). So it seems you can get away with only allocating one. However, as I have mentioned before, I would reach out to the people from the TC39 committee if you want clarification on that. Commented Dec 22, 2018 at 10:33
  • 2
    @FelixKling Here's some discussion: esdiscuss.org/topic/…, esdiscuss.org/topic/iterator-next-method-returning-new-object. Also I found that reusing the object makes escape analysis harder for the compiler...
    – Bergi
    Commented Dec 22, 2018 at 10:45

3 Answers 3

11

Are there under-the-hood optimizations that skip the allocation of the object return by next()?

Yes. Those iterator result objects are small and usually short-lived. Particularly in for … of loops, the compiler can do a trivial escape analysis to see that the object doesn't face the user code at all (but only the internal loop evaluation code). They can be dealt with very efficiently by the garbage collector, or even be allocated directly on the stack.

Here are some sources:

15
  • Cool! I could see at the call site the compiler could figure out the object is short lived but how does the callee/generator know not to allocate the object? Or does the compiler generate two versions of the callee/generator, one that returns an object and ones that uses a no-allocation-protocol? Commented Dec 22, 2018 at 10:16
  • 1
    @ChristopherKing Tbh, I don't know. What I wrote above is just speculation, it's what we could reasonably expect from a compiler, to reason why the protocol as specified is not as bad as you made it sound. I'm gonna search for authoritative sources on whether engines actually implement these optimisations...
    – Bergi
    Commented Dec 22, 2018 at 10:20
  • Thanks. The runtime could see it's short lived and so put it into a gen0 heap but still -- an object is allocated on the heap for each iteration of the loop... Commented Dec 22, 2018 at 10:22
  • 2
    @ChristopherKing They chose to make the iteration protocol simple in the first place, only specifying how it should work, and trusted on engine implementations to optimise. (The simpler the semantics in the spec, the more trivial the written code, the easier to optimise for a compiler). Notice that the ECMAScript specification does not talk about allocations/deallocations at all.
    – Bergi
    Commented Dec 22, 2018 at 10:53
  • 1
    @Bergi jsfiddle.net/AndiTR/5oz9aw8y/12 - Browsers (Chrome v109, FF 115) confirm my results: 1. A (raw) iterator chain (with reused result objects) is 8 x faster than a generator iterator. 2. A chain (sequence + map) with my direct protocol is 2.5 to 4 x faster than the regular protocol.
    – Andi
    Commented Aug 8, 2023 at 21:26
1

Bergi answered already, and I've upvoted, I just want to add this:

Why should you even be concerned about new object being returned? It looks like:

{done: boolean, value: any}

You know, you are going to use the value anyway, so it's really not an extra memory overhead. What's left? done: boolean and the object itself take up to 8 bytes each, which is the smallest addressable memory possible and must be processed by the cpu and allocated in memory in a few pico- or nanoseconds (I think it's pico- given the likely-existing v8 optimizations). Now if you still care about wasting that amount of time and memory, than you really should consider switching to something like Rust+WebAssembly from JS.

2
  • 2
    The overhead is the object itself... But maybe you're right. Maybe one simply shouldn't worry about memory pressure if one is coding Javascript. Still, it just seems that allocating an object for each iteration is memory gluttony even for a dynamic language! Commented Dec 22, 2018 at 10:26
  • @ChristopherKing jsfiddle.net/AndiTR/5oz9aw8y/latest
    – Andi
    Commented Aug 9, 2023 at 9:08
0

The iterator protocol using result objects may be one cause for native Iterator helpers (currently implemented only in Google Chrome >= v122) being slower than my own implementation which internally uses a "direct" interface:

interface DirectIterator<T, TReturn = any> {
    _next(): T | Symbol.for('done');
    _return?(value?: TReturn): TReturn;
}

... and optionally reuses the result object. The following benchmark suite demonstrates it. "Native" benchmarks are only included if globalThis.Iterator exists: https://jsfiddle.net/AndiTR/5oz9aw8y/latest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.