当前位置:编程学习 > JAVA >>

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>

补充:web前端 , JavaScript ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,