【宇潤日常瘋測-004】JS 遍歷陣列如何快!快!快!
阿新 • • 發佈:2018-12-11
首先,我就是一後端全棧,對前端也只是會用罷了。閒的無聊來測測,不深究,只看表面,不喜勿噴!
遍歷陣列在寫 JS
程式碼時候一定是經常用的,那麼怎麼遍歷能達到最高效率呢,很多人一定沒有測試過!
測試環境: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
能不用盡量不用,效能太差了!