Javascript中for循環的三種寫法的效率對比

 

一共三種寫法 如下:

 

view sourceprint?for (var i = 0; i < arr.length; i++)

 

view sourceprint?for (var i in arr)

 

view sourceprint?for (var i = 0, len = arr.length; i < len; i++)

 

先看下運行測試的界面:

 

 

 

再看下對應的三個結果,三種寫法執行的效率是有很大不同的:

 

 

 

如此看來,執行效率最快的是第三種:

 

view sourceprint?for (var i = 0, len = arr.length; i < len; i++)

 

先聲明變量,再進行循環判斷,效率遠比遍歷數組高得多,也比循環取得數組長度的效率快得多!

 

下面是頁面源代碼:

 

view sourceprint?<html> 

 

<body> 

 

<script type="text/javascript"> 

 

  

 

function makeArr(num) { 

 

    var arr = []; 

 

    for (var i = 0; i<num; i++){ 

 

        arr.push('abc'); 

 

    } 

 

    arr.join(''); 

 

    return arr; 

 

 

var num = 10000000; 

 

function function1() { 

 

    var arr = makeArr(num); 

 

    var start = (new Date()).valueOf(); 

 

    var count = 0; 

 

    for (var i = 0; i < arr.length; i++) { 

 

        count++; 

 

    } 

 

    var end = (new Date()).valueOf(); 

 

    console.log('Count: '+count+' times'); 

 

    console.log('Time spent: '+(end – start)); 

 

 

function function2() { 

 

    var arr = makeArr(num); 

 

    var start = (new Date()).valueOf(); 

 

    var count = 0; 

 

    for (var i in arr) { 

 

        count++; 

 

    } 

 

    var end = (new Date()).valueOf(); 

 

    console.log('Count: '+count+' times'); 

 

    console.log('Time spent: '+(end – start)); 

 

 

function function3() { 

 

    var arr = makeArr(num); 

 

    var start = (new Date()).valueOf(); 

 

    var count = 0; 

 

    for (var i = 0, len = arr.length; i < len; i++) { 

 

        count++; 

 

    } 

 

    var end = (new Date()).valueOf(); 

 

    console.log('Count: '+count+' times'); 

 

    console.log('Time spent: '+(end – start)); 

 

 

  

 

  

 

  

 

</script> 

 

  

 

for (var i = 0; i < arr.length; i++) <br /> 

 

<button onClick="function1();">loop 1</button><br /> 

 

<p id="f1"></p> 

 

  

 

for (var i in arr)<br /> 

 

<button onClick="function2();">loop 2</button><br /> 

 

<p id="f2"></p> 

 

  

 

for (var i = 0, len = arr.length; i < len; i++)<br /> 

 

<button onClick="function3();">loop 3</button><br /> 

 

<p id="f3"></p> 

 

  

 

</body> 

 

</html>

You May Also Like