I often use Array.from()
or [...foo]
to get an array of iterable objects. I can also repeat it and click on the array manually instead, but I would prefer the native one, because it was very simple, and I thought that its implementation would be more efficient.
However, I found some test result that shows that that native path is slower .
https://jsperf.com/set-iterator-vs-foreach/4
I also ran tests with fewer (50) or more (10 thousand) elements in Chrome and Firefox, but I got a similar result.
https://jsfiddle.net/unarist/k0cu8wta/2/
I understand that itβs [...foo]
faster than Array.from()
because I Array.from()
have to process objects like array and parameter mapFn
, but I could not find a plausible reason between [...foo]
and for..of
+ push()
.
What makes for..of
+ push()
faster than Array.from()
u [...foo]
?
Update: My concern is not how fast and what should I use. I was surprised that the native version is slower than the JS version, and I wanted to know why, because I thought "in general, the native is fast."
(for example, a native has more work than a loop + push path, special optimization for something, etc.)
I tested Chrome 60 and Firefox 54 on Windows 10 x64.
source
share