前言
在JS中有许多的方法可以对可遍历对象进行遍历,但是性能各有不同,现在我就对不同方法做个小小的测试,看看哪些循环方法性能是比较高的
测试代码
测试的内容是给一个存有1千万个1的数组,分别计算和
- for of
let sum = 0; const of_start_time = new Date().getTime(); for (let item of array) { sum += item; } const of_end_time = new Date().getTime(); console.log(`of-- sum:${sum} --${of_end_time - of_start_time}`); - for in
sum = 0; const in_start_time = new Date().getTime(); for (let index in array) { sum += array[index]; } const in_end_time = new Date().getTime(); console.log(`in-- sum:${sum} --${in_end_time - in_start_time}`); - while
sum = 0; let count = 0; const while_start_time = new Date().getTime(); while (count < array.length) { sum += array[count]; count++; } const while_end_time = new Date().getTime(); console.log(`while-- sum:${sum} --${while_end_time - while_start_time}`); - for
sum = 0; const start_time = new Date().getTime(); for (let index = 0; index < array.length; index++) { sum += array[index]; } const end_time = new Date().getTime(); console.log(`-- sum:${sum} --${end_time - start_time}`); - Array.each
sum = 0; const each_start_time = new Date().getTime(); array.forEach((item) => { sum += item; }); const each_end_time = new Date().getTime(); console.log(`each-- sum:${sum} --${each_end_time - each_start_time}`); - lodash-foreach
sum = 0; const lodash_each_start_time = new Date().getTime(); _.forEach(array, (item) => { sum += item; }); const lodash_each_end_time = new Date().getTime(); console.log(`lodash-each-- sum:${sum} --${lodash_each_end_time - lodash_each_start_time}`); - lodash-forIn
sum = 0; const lodash_in_start_time = new Date().getTime(); _.forIn(array, (value, key, obj) => { sum += value; }); const lodash_in_end_time = new Date().getTime(); console.log(`lodash-in-- sum:${sum} --${lodash_in_end_time - lodash_in_start_time}`);
测试结果

测试结论
从结果上来看,for,while的性能相差不大,属于性能最好的两个,并且从多次测试结果来看,while的性能是略优于for的。for of则稍逊于前两个,但是也远超于其他的。其次则是Array.foreach和lodash的foeach了,loadsh的foreach性能上又略优于Array.foreach。对于循环遍历key值的方式,性能是最差的,而且差别特别的大,所以在日常代码开发中我认为要尽量避免使用for in,并且我对lodash的forIn也做了测试,结果出乎意料,远差于原生的for in循环,所以如果实在要遍历key的话,还是用原生的for in吧。当然如果我们不使用原生的for in去遍历key,当我们需要遍历key的时候依旧逃脱不了用Object.keys去获取所有的key,所以我同时对Object.keys做了个测试,发现也需要花费1100-1200ms的时间,所以大致来说,如果我们真的需要遍历key的话,用for in是没有问题的。我依旧顺手对lodash的keys方法做了测试,性能还是远差于原生方法,所以大家就不要用了。
4万+



被折叠的 条评论
为什么被折叠?



