首先,我就是一后端全栈,对前端也只是会用罢了。闲的无聊来测测,不深究,只看表面,不喜勿喷!

遍历数组在写 JS 代码时候一定是经常用的,那么怎么遍历能达到最高效率呢,很多人一定没有测试过!

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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 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 能不用尽量不用,性能太差了!

相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!