> To complete an operation like `const [a, b] = function_that_returns_an_array()`, JavaScript constructs an iterator that iterates through the array instead of directly indexing from the array
This is interesting. Why doesn't JS just directly index arrays for destructuring?
Any object can become iterable by adding Symbol.iterator, and destructuring should work for them. You can even patch Symbol.iterator on arrays itself, and the VM has to cope:
The terrible performance of the iterator protocol was discussed and ignored at the time, by saying that escape analysis would solve it [0]. Nearly 10 years later, and escape analysis has still not solved it. It's extremely GC-hungry and still sucks. It's just a bad spec, designed by people who are not performance-conscious.
It might make sense for engines to specialize destructuring assignment and splicing of Arrays to remove their iterator protocol overhead (if the user hasn't patched Symbol.iterator) but that's a whole other can of worms.
Also, what's even more crazy is that destructuring {0: foo, 1: bar} can be faster in some javascript engines when destructuring an array with two or three element.
Yeah, absolutely. With the linked benchmark I just got the following results on desktop Linux:
- 17M ops/s ± 1.65% for array destructuring in Chrome
- 169M ops/s ± 0.78% for object destructuring in Chrome
- 545M ops/s ± 3.68% for array destructuring in Firefox
- 81M ops/s ± 0.8% for object destructuring in Firefox
So per the principle of "optimize for the bottleneck", one could choose to use object destructuring, because the slowest Firefox is still comparable to the fastest Chrome option. Or when, for example, you're running Node on a server and know which JS engine you're using.
This is interesting. Why doesn't JS just directly index arrays for destructuring?