Javascript中for循环的三种写法的效率对比
时间:2011-07-24 09:14来源: 作者: 点击:
次
一共三种写法 如下:
for (var i = 0; i < arr.length; i++)
for (var i in arr)
一共三种写法 如下:
for ( var i = 0; i < arr.length; i++) |
for ( var i = 0, len = arr.length; i < len; i++) |
先看下运行测试的界面:
再看下对应的三个结果,三种写法执行的效率是有很大不同的:
如此看来,执行效率最快的是第三种:
for ( var i = 0, len = arr.length; i < len; i++) |
先声明变量,再进行循环判断,效率远比遍历数组高得多,也比循环取得数组长度的效率快得多!
下面是页面源代码:
<script type= "text/javascript" > |
for ( var i = 0; i<num; i++){ |
var start = ( new Date()).valueOf(); |
for ( var i = 0; i < arr.length; i++) { |
var end = ( new Date()).valueOf(); |
console.log( 'Count: ' +count+ ' times' ); |
console.log( 'Time spent: ' +(end - start)); |
var start = ( new Date()).valueOf(); |
var end = ( new Date()).valueOf(); |
console.log( 'Count: ' +count+ ' times' ); |
console.log( 'Time spent: ' +(end - start)); |
var start = ( new Date()).valueOf(); |
for ( var i = 0, len = arr.length; i < len; i++) { |
var end = ( new Date()).valueOf(); |
console.log( 'Count: ' +count+ ' times' ); |
console.log( 'Time spent: ' +(end - start)); |
for ( var i = 0; i < arr.length; i++) <br /> |
<button onClick= "function1();" >loop 1</button><br /> |
<button onClick= "function2();" >loop 2</button><br /> |
for ( var i = 0, len = arr.length; i < len; i++)<br /> |
<button onClick= "function3();" >loop 3</button><br /> |
(责任编辑:admin) |
织梦二维码生成器
------分隔线----------------------------