首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

JS 遍历数组如何快!快!快!

Sonder
2020-12-23
1801字
5分钟
浏览 (2.7k)

测试环境:Chrome 71.0.3578.80 + F12 开发者工具

此次测试,我使用 6 种方法进行测试,它们分别是:2种 for 、forEach、for in、for of以及map。

复制代码
var list = [];
for(var i = 0; i < 100000; ++i)
{
   list.push(Math.random());
}

function test1(list)
{
   var s = 0;
   for(var i = 0; i < list.length; ++i)
   {
       s += i;
   }
   return s;
}

function test2(list)
{
   var s = 0;
   var count = list.length;
   for(var i = 0; i < count; ++i)
   {
       s += i;
   }
   return s;
}

function test3(list)
{
   var s = 0;
   list.forEach(function(value){
       s += value;
   });
   return s;
}

function test4(list)
{
   var s = 0;
   for(var i in list)
   {
       s += list[i];
   }
   return s;
}

function test5(list)
{
   var s = 0;
   list.map(function(value){
       s += value;
   });
   return s;
}

function test6(list)
{
   var s = 0;
   for(let value of list) {  
      s += value;
   };
   return s;
}

console.time('list.length')
test1(list);
console.timeEnd('list.length');

console.time('count')
test2(list);
console.timeEnd('count');

console.time('forEach')
test3(list);
console.timeEnd('forEach');

console.time('for in')
test4(list);
console.timeEnd('for in');

console.time('map')
test5(list);
console.timeEnd('map');

console.time('for of')
test6(list);
console.timeEnd('for of');

测试结果

复制代码
list.length: 2.52294921875ms

count: 2.19775390625ms

forEach: 3.802978515625ms

for in: 23.849853515625ms

map: 33.470947265625ms

for of: 7.194091796875ms

结论

以下结论仅供参考,仅在单纯遍历数组时有效,如果有其它需求可能不适用,请自行取舍。

**性能最佳:**定义一个变量,把list.count存起来,然后 < 这个变量作为条件来循环。

当然,直接for循环将list.count作为条件来循环,性能也不比上面的差多少,偷懒也是可以用的。

forEach、for of 性能也还行。

for in 和 map 能不用尽量不用,性能太差了!

转载于:https://blog.yurunsoft.com/a/134.html

下一篇 / 分享8个Vue自定义指令

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)