Trying to Map an Array, which one of these implementations is better performance-wise? Is there a better solution?
//Given the following Array of people:
const people = [ { name: 'Alice', available: true }, { name: 'Bob', available: false }, { name: 'Charlie', available: true }];
const mapWithReduce = (people) => people.reduce((map, person) => ({ [person.name]: person.available, ...map }), {});
const mapWithForEach = (people) => {
const map = {};
people.forEach((person) => map[person.name] = person.available);
return map;
}
I find mapWithReduce prettier but I don't know if ...map} is copying the map every iteration. mapWithForEach seems more performant.
I like this solution.
const people = [ { name: 'Alice', available: true }, { name: 'Bob', available: false }, { name: 'Charlie', available: true } ]; const peopleMap = people.reduce((map, person) => { map[person.name] = person; return map; }, {}); console.log(peopleMap);
Looks equals than the forEach solution but without creating local vars.
Performance-wise, using a for
loop is the fastest.
const people = [{ name: 'Alice', available: true }, { name: 'Bob', available: false }, { name: 'Charlie', available: true }] const mapWithForLoop = (key, value) => array => { const map = {} for (let i = 0; i < array.length; i++) { const entry = array[i] map[entry[key]] = entry[value] } return map } const mapPeopleWithForLoop = mapWithForLoop('name', 'available') console.log(mapPeopleWithForLoop(people))
The forEach()
method comes close, though.
they should both be identical if you make their implementations the same and reduce is a little easier to grok because developers know that it has an accumulator whereas in the forEach, you're just sort of implementing reduce yourself
const mapWithReduce = (people) => people.reduce((map, person) =>
{
map[person.name]: = person.available;
return map
}, {}
);
edit: it's possible that under the hood forEach
is more performant, but if you're using babel or another transpiler, it's probably a moot point because at this point, they should do the work of making the more idiomatic version performant. ( source )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.