[JS] 배열을 객체로 바꾸는 방법 속도 비교 (forEach VS. reduce)
0. 참고
https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_of/
Performance of JavaScript .forEach, .map and .reduce vs for and for..of
Declarative programming is better 95% of the time. However, when performance matters, imperative style is the go-to solution.
leanylabs.com
요지
- JS에서 iterable obejct를 변환하는 다양한 방법들이 있다.
- 가독성 측면에서는 선언형 프로그램이 나을 수 있으나 성능 측면에서는 명령형 프로그래밍이 나음
- Array 객체의 메서드 보다는 for 또는 for...of 로 순환하는 것이 보다 우수한 성능을 가짐.
1. 궁금증
forEach VS. reduce 성능 비교
2. 비교할 코드
- 개요: 프론트에서 넘어온 객체의 배열을 하나의 객체로 바꾸는 작업
- Array.reduce
async function reducerForDB(array) {
console.log(array)
const result = await array.reduce((acc, cur) => {
acc[cur.value] = cur.selected;
return acc;
}, {});
console.log(result)
return result;
}
export { reducerForDB };
- Array.forEach
async function getObjectForDB(array) {
console.log(array)
const result = {};
await array.forEach(el => {
result[el.value] = el.selected;
});
console.log(result)
return result;
}
export { getObjectForDB };
3. 테스팅
console.log("start")
let timeAcc = 0
let count = 0
const interval = setInterval(async () => {
count += await 1
const start = +new Date()
const languageUpdate = await reducerForDB(language); // reduce OR forEac
const end = await +new Date()
const diff = await end - start
timeAcc += await diff
console.log("time:", diff)
console.log("timeAcc", timeAcc)
console.log("count:", count)
}, 1000)
setTimeout(() => {
clearInterval(interval)
console.log("timeAcc:", timeAcc, "count: ", count)
console.log("Avg: ", timeAcc/count)
}, 31000)
4. 결과
- Array.reduce
- Array.forEach
5. 결과 해석
- 큰 차이가 없다.
- reduce나 foreach나 전후로 console을 출력하는게 시간을 잡아먹는 변수 같아, console.log을 지우고 다시 테스팅해보았다. milisecond 단위로 측정함에도 불구하고 시간 차이가 0으로 찍혀, 테스팅이 무의미해졌다.
- 배열의 크기를 키워 다시 측정해보았으나 역시 큰 차이가 없다
6. 결론
- console.log는 정말 시간을 많이 잡아먹는다. 서비스 출시 전에 무조건 지우자
- 엄청난 양의 데이터가 아니면 가독성을 고려하여 reduce, forEach를 써도 나쁘지 않다.
- reduce와 forEach는 취향 차이,,,?