|
1
2
3
4
|
var props = [‘prop1‘, ‘prop2‘],i = 0;whlie(i < props.length){ precess(object[props[i++]]);} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
window.onload = function(){var items = Array(1000000).join(‘,‘).split(‘,‘).map(function(item, index) { return index;}); console.log(forCircle()) console.log(whileCircle()) console.log(doCircle())function forCircle(){console.profile();var currTime = new Date(); var tal = 0; for(var i = 0;i < items.length; i++){ tal = tal + process(items[i]); } console.profileEnd(); console.log(‘forCircle用时:‘ + (new Date() - currTime) + ‘ms‘); return tal;}function whileCircle(){console.profile();var currTime = new Date(); var tal = 0; var j = 0; while (j < items.length){ tal = tal + process(items[j++]); } console.profileEnd(); console.log(‘whileCircle用时:‘ + (new Date() - currTime) + ‘ms‘); return tal;}function doCircle(){console.profile();var currTime = new Date(); var tal = 0; var k = 0; do{ tal = tal + process(items[k++]); }while (k < items.length) console.profileEnd(); console.log(‘doCircle用时:‘ + (new Date() - currTime) + ‘ms‘); return tal;}function process(item){ return item*100;}} |
取某次测试结果:



平均来说,for循环耗时8ms,while耗时4ms,doWhile耗时也是4ms。for是最慢的。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
for(var i = 0;i < items.length; i++){ process(items[i]);}//var j = 0;while (j < items.length){ process(items[j++]);}//var k = 0;do{ process(items[k++]);}while (k < items.length) |
在这个循环中,每次运行都会产生如下操作:
①查找一次属性(items.length)
②执行数值比较一次(i < items.length)
③查看控制条件是否为true(i < items.length ==true)
④一次自增操作(i++)
⑤一次数组查找(items[i])
⑥一次函数调用(process(items[i]))
若把数组长度存到一个局部变量,那么就不需要每次都查找一次items.length,也就提高了性能。
改为这样:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
for(var i = 0, len = items.length;i < len; i++){ process(items[i]);}//var j = 0,count = items.length;while (j < count){ process(items[j++]);}//var k = 0,num = items.length;do{ process(items[k++]);}while (k < num) |
这样在大多数浏览器中能节省大概25%的运行时间(IE中甚至可以节省50%)。总的来说,循环次数大的情况下,运行时间确实有提升。取某次结果如下:
没有局部存量存储数组长度时:

有局部变量存储数组长度时:

|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
var iterations = Math.floor(items.length/8), startAt = items.length%8, i = 0; do{ switch(startAt){ case 0 : process(items[i++]); case 7 : process(items[i++]); case 6 : process(items[i++]); case 5 : process(items[i++]); case 4 : process(items[i++]); case 3 : process(items[i++]); case 2 : process(items[i++]); case 1 : process(items[i++]); } startAt = 0; }while(--iterations); |
原文:http://www.cnblogs.com/Leo_wl/p/6392150.html