前言:
數組遍歷有很多種方法,雖然不同方法有不同的特性及適用環境,除了普通飛for循環之外,for...in能直接輸出數組元素的索引,for...of能直接輸出數組元素的值,map則可以直接生成新的數組,forEach則可以遍歷修改元祖元素的值。那么這些方法在性能上相比怎么樣呢?
驗證:
為了驗證這個問題,構造了一個10000條數據的數組,然后使用不同的方法對數組進行遍歷輸出,通過每種方法遍歷前后的時間戳來計算每種方法執行耗費的時間,整理如下:
如上,使用谷歌瀏覽器進行了10次實驗,得出每種方法的執行時間(ms),其中優化版for循環是使用臨時變量,將長度緩存起來,避免重復獲取數組長度。
大致可以看出性能最優的要數優化版的for循環了,其次是for...of和for...in循環,最差的集中在forEach循環,其次是map遍歷,普通的for循環則處於中間。
驗證代碼:
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 </head> 8 9 <body> 10 <script> 11 //構造數組 12 var arr = []; 13 for(let i = 0; i < 10000; i++) { 14 arr[i] = { 15 detailImgUrl: "https: //ss0.bdstatic.com/k4oZeXSm1A5BphGlnYG/skin/71.jpg?2" 16 } 17 } 18 //console.log(arr) 19 //數組遍歷驗證 20 const {log} = console; 21 var newArr = [] 22 //方法1 普通for循環 23 let time = new Date().getTime(); 24 for(i = 0; i < arr.length; i++) { 25 document.write(arr[i].detailImgUrl) 26 } 27 let time1 = new Date().getTime() 28 log(time1 - time, "普通for循環") 29 newArr.push(time1 - time) 30 //方法2 優化版for循環 31 for(j = 0, len = arr.length; j < len; j++) { 32 document.write(arr[j].detailImgUrl) 33 } 34 let time2 = new Date().getTime() 35 log(time2 - time1, "優化版for循環") 36 newArr.push(time2 - time1) 37 //方法3 forEach循環 38 arr.forEach(item => { 39 document.write(item.detailImgUrl) 40 }) 41 let time3 = new Date().getTime() 42 log(time3 - time2, "forEach循環") 43 newArr.push(time3 - time2) 44 //方法4 for in循環 45 for(k in arr) { 46 document.write(arr[k].detailImgUrl) 47 } 48 let time4 = new Date().getTime() 49 log(time4 - time3, "for in循環") 50 newArr.push(time4 - time3) 51 //方法5 for of循環 52 for(k of arr) { 53 document.write(k.detailImgUrl) 54 } 55 let time5 = new Date().getTime() 56 log(time5 - time4, "for of循環") 57 newArr.push(time5 - time4) 58 //方法6 map遍歷 59 arr.map(v => { 60 document.write(v.detailImgUrl) 61 }) 62 let time6 = new Date().getTime() 63 log(time6 - time5, "map遍歷") 64 newArr.push(time6 - time6) 65 newArr.forEach(value => { 66 document.write("<p>" + value + "</p>") 67 }) 68 </script> 69 </body> 70 71 </html>
注意事項:
1.為了增加實驗的復雜度,以對象作為數組元素,且以比較長的字符串作為對象的一個元素,使用各種數組遍歷方法去遍歷對象元素的子元素;
2.為了更真實的反應各種遍歷方法的性能,建議數組長度在1000以上,實驗次數在10次以上,這樣才能得出更真實的對比結果;
3.測試數據比較大,可以先用普通的for循環生成數組,然后直接使用數組進行實驗;
總結:
對於前邊的實驗結果,也只有數據量比較大的情況下才會比較明顯。通常情況下前端一次處理的數組也就幾十條,將各結果按比例折算,最差的也就10.89ms,最好的8.08ms,相差了2~3ms左右,這個幾乎可以忽略不計了。所以說非大數據的情況下如果對性能要求不是太嚴格就不用太糾結了,根據自己的習慣使用就好。當然追求性能的同學可以在實際開發中選擇性能比較好的方法進行使用。