js array for loop performance compare All In One
js array for loop performance compare All In One
for...of, for...in, Array.map, Array.forEach, while
js Array for loop performance
// const boxes = [...``.padStart(10, ` `)].map((item, i) => ({}));
const boxes = [...``.padStart(1, ` `)].map((item, i) => ({}));
const creative_ids_map = [...``.padStart(1000000, ` `)].map((item, i) => ({
creative_id: i + 1,
creative_name: `${i + 1}`,
}));
const creative_boxes = [];
const start = new Date().getTime();
console.log("once_time", start);
boxes.forEach(item => {
const creativeIds = [];
const creativeIdsMap = [];
// creative_ids_map 需要 for 循环一次 (👎代码行数多,👍循环次数少)
for (const obj of creative_ids_map) {
const {
creative_id,
creative_name,
} = obj;
creativeIds.push(creative_id);
creativeIdsMap.push({
creative_id,
creative_name,
});
}
creative_boxes.push({
creative_ids: creativeIds,
creative_ids_map: creativeIdsMap,
});
});
const end = new Date().getTime();
console.log("once_time", end);
console.log("once cost time", (end - start));
// const boxes = [...``.padStart(10, ` `)].map((item, i) => ({}));
const boxes = [...``.padStart(1, ` `)].map((item, i) => ({}));
const creative_ids_map = [...``.padStart(1000000, ` `)].map((item, i) => ({
creative_id: i + 1,
creative_name: `${i + 1}`,
}));
const creative_boxes = [];
const start = new Date().getTime();
console.log("twice_time", start);
boxes.forEach(item => {
// creative_ids_map 需要 for 循环两次 (👍代码行数少,👎循环次数多)
const creativeIds = creative_ids_map.map(obj => obj.creative_id) || [];
const creativeIdsMap = creative_ids_map.map(obj => ({
creative_id: obj.creative_id,
creative_name: obj. creative_name,
})) || [];
creative_boxes.push({
creative_ids: creativeIds,
creative_ids_map: creativeIdsMap,
});
});
const end = new Date().getTime();
console.log("twice_time", end);
console.log("twice cost time", (end - start));
testing
https://levelup.gitconnected.com/which-is-faster-for-for-of-foreach-loops-in-javascript-18dbd9ffbca9
https://blog.bitsrc.io/measuring-performance-of-different-javascript-loop-types-c0e9b1d193ed
https://leanylabs.com/blog/js-forEach-map-reduce-vs-for-for_of/
refs
https://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript
https://jsben.ch/wY5fo
https://alligator.io/js/foreach-vs-for-loops/
https://felixgerschau.com/foreach-vs-map-javascript/
https://blog.kuzzle.io/efficiently-iterate-on-javascript-arrays
https://www.freecodecamp.org/news/how-to-optimize-your-javascript-apps-using-loops-d5eade9ba89f/
https://www.section.io/engineering-education/javascript-iterations-which-one-is-faster/
https://javascript.plainenglish.io/which-type-of-loop-is-fastest-in-javascript-ec834a0f21b9
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15441242.html
未经授权禁止转载,违者必究!