4 ms·
> To complete an operation like `const [a, b] = function_that_returns_an_array()`, JavaScript constructs an iterator that iterates through the array instead of
by bryancoxwell 2y ago
> 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?
- vanderZwan 2y agoBecause things like proxies exist, I guess. 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.
- bryancoxwell 2y agoQuite a bit faster it looks like: https://jsbench.me/6zlvrupqmj/1 https://jsbench.me/6zlvrupqmj/1
- debugnik 2y ago91.86% slower on my Android phone with Firefox, so it definitely depends on which JS engine.
- vanderZwan 2y agoYeah, 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.
- vbezhenar 2y ago77M ops/s ± 0.31%; 1.3B ops/s ± 0.17% for Safari. Difference is huge 800M ops/s ± 0.5%; 837M ops/s ± 0.32% for Chrome on the same computer.
- Alifatisk 2y agoWhat a cool website!
- Jasper_ 2y agoAny 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: > Array.prototype[Symbol.iterator] = function*() { yield 1; yield 2; yield 3; } > [...[4, 5, 6]] [1, 2, 3] 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. [0] https://esdiscuss.org/topic/performance-of-iterator-next-as-specified https://esdiscuss.org/topic/performance-of-iterator-next-as-...