Memory Friendly Array Mapping With `Array.from()`
Memory Efficiency
JavaScript’s static Array method Array.from()
has a second parameter that
allows you to efficiently map over an array as it’s copied to avoid creating an
intermediate array.
const elements = document.querySelectorAll('*');
const elementClasses = Array.from(elements, getNodeClasses);
function getNodeClasses(node: Element) {
const { classList } = node;
return classList;
}
vs
const elements = document.querySelectorAll('*');
const elementClasses = [...elements].map(getNodeClasses); // creates intermediate array
function getNodeClasses(node: Element) {
const { classList } = node;
return classList;
}
Resources
- MDN docs on
Array.from()