首先,我就是一后端全栈,对前端也只是会用罢了。闲的无聊来测测,不深究,只看表面,不喜勿喷!前端
遍历数组在写 JS
代码时候必定是常常用的,那么怎么遍历能达到最高效率呢,不少人必定没有测试过!后端
测试环境:Chrome 71.0.3578.80 + F12 开发者工具
数组
这次测试,我使用 6 种方法进行测试,它们分别是:2种 for
、forEach
、for in
、for of
以及map
。dom
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
性能也还行。code
for in
和 map
能不用尽可能不用,性能太差了!开发