I often use Array.from()
or [...foo]
to obtain an array from iterable objects. I also can iterate it and push to an array manually instead, but I'd prefer native one because it's much simple and I thought native implementation will be more efficient.
However, I found some benchmark result which shows those native way are slower.
https://jsperf.com/set-iterator-vs-foreach/4
I've also run tests with fewer (50) and more (10k) elements on Chrome and Firefox, but ends up a similar result.
https://jsfiddle.net/unarist/k0cu8wta/2/
I can understand [...foo]
is faster than Array.from()
because Array.from()
have to handle array-like objects and the mapFn
parameter, but I couldn't find a plausible reason about between [...foo]
and for..of
+push()
way.
What makes for..of
+push()
faster than Array.from()
and [...foo]
?
Update: My concern is not how fast nor which should I use. I was surprised about native version is slower than JS version and I wanted to know why, because I thought "generally, native one is fast".
(e.g. native one does more work than loop+push way, special optimization for something, etc.)
I've tested on Chrome 60 and Firefox 54 on Windows 10 x64.