[英]Which one of these ArrayToMap functions usages is better performance-wise?
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. 我发现mapWithReduce更漂亮,但我不知道... map}是否在每次迭代中都复制地图。 mapWithForEach seems more performant.
mapWithForEach似乎更有效。
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. 看起来比forEach解决方案相等,但没有创建本地var。
https://jsperf.com/arraymapeachreduce/9 https://jsperf.com/arraymapeachreduce/9
Performance-wise, using a for
loop is the fastest. 在性能方面,使用
for
循环最快。
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. 但是,
forEach()
方法接近。
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 如果您使它们的实现相同,并且应该简化reduce,它们应该都相同,因为开发人员知道它有一个累加器,而在forEach中,您只是在实现reduce自己
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. 编辑:有可能
forEach
的性能更高,但是如果您使用的是babel或其他编译器,那么这可能是一个有争议的问题,因为在这一点上,他们应该努力使版本更加惯用。 ( source ) ( 来源 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.