[英]Performance-wise,algorithmic complexity-wise which of the following two JS fucntion for capitializing the first letter of a string is better and why?
[英]Which one of these ArrayToMap functions usages is better performance-wise?
嘗試映射數組,以下哪種實現在性能上更好? 有更好的解決方案嗎?
//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;
}
我發現mapWithReduce更漂亮,但我不知道... map}是否在每次迭代中都復制地圖。 mapWithForEach似乎更有效。
我喜歡這個解決方案。
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);
看起來比forEach解決方案相等,但沒有創建本地var。
在性能方面,使用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))
但是, forEach()
方法接近。
如果您使它們的實現相同,並且應該簡化reduce,它們應該都相同,因為開發人員知道它有一個累加器,而在forEach中,您只是在實現reduce自己
const mapWithReduce = (people) => people.reduce((map, person) =>
{
map[person.name]: = person.available;
return map
}, {}
);
編輯:有可能forEach
的性能更高,但是如果您使用的是babel或其他編譯器,那么這可能是一個有爭議的問題,因為在這一點上,他們應該努力使版本更加慣用。 ( 來源 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.