[Javascript] Improve performance of Array.reduce
Compare two code snippet
const people = [
{id: 1,name: 'John', age: 45},
{id: 2,name: "Op", age: 32},
{id: 3, name: "Wade",age: 39 }
]
// option 1
const res = people.reduce((acc, curr) => {
return ({
...acc,
[curr.id]: curr
})
},{})
// option 2
const res2 = people.reduce((acc, curr) => {
acc[curr.id] = curr
return acc
},{})
Both options achieve the same result, which is converting an array of objects into an object with keys based on the 'id' property. However, there are some differences in performance and readability.
Option 1:
const res = people.reduce((acc, curr) => {
return ({
...acc,
[curr.id]: curr
})
},{})
This option uses the spread operator to create a new object with the previous accumulator content and the new key-value pair. While this approach is easier to read and understand for some developers, it can be less efficient, as it creates a new object on each iteration.
Option 2:
const res2 = people.reduce((acc, curr) => {
acc[curr.id] = curr
return acc
},{})
This option modifies the accumulator object in-place by adding a new key-value pair on each iteration. This approach is generally more efficient, as it doesn't create a new object on each iteration.
Based on the trade-offs, I would recommend Option 2 for better performance, especially if you're working with large datasets. However, if readability is a higher priority and performance is not a major concern, you might prefer Option 1.
Now, let's see this code:
const numbers = [1,2,3,4,5]
numbers.reduce((acc, curr) => {
return [
...acc,
curr * 100
]
}, [])
You might think apply the same idea to improve the performance:
numbers.reduce((acc, curr) => {
acc.push(curr * 100)
return acc
}, [])
Nope, actually, you can just use .map:
const result = numbers.map(number => number * 100);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-04-07 [AWS] Lab: Docker and CodeCommit Part 1
2021-04-07 [AWS] Lab: Docker with CodeCommit & CodeBuild Part2
2019-04-07 [Algorithm] Longest Substring Without Repeating Characters?
2016-04-07 [Angular 2] Using Promise to Http
2016-04-07 [Angular 2] *ngFor with index