前言:html
數組遍歷有不少種方法,雖然不一樣方法有不一樣的特性及適用環境,除了普通飛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次以上,這樣才能得出更真實的對比結果;spa
3.測試數據比較大,能夠先用普通的for循環生成數組,而後直接使用數組進行實驗;
總結:
對於前邊的實驗結果,也只有數據量比較大的狀況下才會比較明顯。一般狀況下前端一次處理的數組也就幾十條,將各結果按比例折算,最差的也就10.89ms,最好的8.08ms,相差了2~3ms左右,這個幾乎能夠忽略不計了。因此說非大數據的狀況下若是對性能要求不是太嚴格就不用太糾結了,根據本身的習慣使用就好。固然追求性能的同窗能夠在實際開發中選擇性能比較好的方法進行使用。