[...a].filter
vs Array.from(a).filter
Not a "real" difference in performance, Array.from
could be a very very tiny bit faster because you're not creating a new Array
on the "JS level", but it happens directly in the native code.
Performance - consider not using either
However for performance (and to also avoid "Array
-ing") you should consider why are you filtering a NodeList
and where/how did you get it. In many cases, you just want a particular element either by id
or by class
or other CSS selector.
document.querySelectorAll
is like 10x - 200x faster and works for any CSS selector
document.getElementById
is even faster (but of course requires an id
)
You can even optimize querySelectorAll
or bypass "not-yet-known" case if you provide a pre-stored parent to look in, let me give you an example:
let mainbar = document.getElementById('mainbar');
mainbar.querySelectorAll('.flex--item');
is almost 10x faster than
Array.from(a).filter(el => el.classList.contains("flex--item"))
Also be aware that document.querySelectorAll('#mainbar .flex--item');
is still about 5x faster than Array
filtering, but about 2x slower than pre-storing the parent with an id
.
Besides better performance, you will also always get NodeList
(it may be empty, but it still will be NodeList
) and that goes for both document.querySelectorAll()
and Element.querySelectorAll()
babel
, then[...coll]
will simply callArray.from(coll)
for anything that is not anArray
. – Threatt...
syntax may be unsupported by older IDEs whileArray.from()
is just a regular method. – Tibbetts