Javascript中八种遍历方法的执行速度深度对比(3)

注: array数组默认为空, 依次赋值数组长度为1 000 000, 10 000 000, 100 000 000, 分别在 Chrome, Firefox, Safari 浏览器上进行两轮测试, 取测试时间平均值作为比较对象, 时间单位为ms. 如下是测试代码:

var array = [], length = array.length = 10000000;//(一千万) //for(var i=0;i<length;i++){ // array[i] = 'louis'; //} console.log(array[0]); //-------------------------for var t1 = +new Date(); for(var i=0;i<length;i++){ } var t2 = +new Date(); console.log('for:' + (t2-t1)); //-------------------------do/while var t1 = +new Date(); var i = 0; do { i++; } while(i<length); var t2 = +new Date(); console.log('do while:' + (t2-t1)); //-------------------------forEach var t1 = +new Date(); array.forEach(function(item){ }); var t2 = +new Date(); console.log('forEach:' + (t2-t1)); //-------------------------for in var t1 = +new Date(); for(var item in array){ } var t2 = +new Date(); console.log('for in:' + (t2-t1)); //------------------------- $.each var t1 = +new Date(); $.each(array, function(i, ele){ }); var t2 = +new Date(); console.log('$.each:' + (t2-t1)); //-------------------------$().each var t1 = +new Date(); $(array).each(function(i,ele){ }); var t2 = +new Date(); console.log('$(ele).each:' + (t2-t1)); //-------------------------map var t1 = +new Date(); array.map(function(num){ }); var t2 = +new Date(); console.log('map:' + (t2-t1)); //-------------------------every var t1 = +new Date(); array.every(function(e,i,arr){ }); var t2 = +new Date(); console.log('every:' + (t2-t1));

测试机器正常运行 IDE, 编辑器, 浏览器, qq, 微信等常用应用, 系统空闲. 硬件设备如下:

操作系统: OSX EI Capitan 版本 10.11.5

MacBook Pro(13 英寸,2015 年初期)

处理器: 2.7 GHz Intel Core i5

内存: 8 GB 1867 MHz DDR3

以上多轮测试结果汇总如下三张表(单位:ms):

数组长度为10^6


数组长度为10^6 chrome 52.0.2743.116 (64-bit) Firefox Developer Edition 49.0a2 (2016-08-01) Safari 9.1.1 (11601.6.17)
for   (16+19)/2 = 17.5   (6+7)/2 = 6.5   (6+7)/2 = 6.5  
do while   (24+17)/2 = 20.5   (7+5)/2 = 6   (5+5)/2 = 5  
for in   (19+28)/2 = 23.5   (0+0)/2 = 0   (0+0)/2 = 0  
forEach   (41+28)/2 = 34.5   (4+4)/2 = 4   (31+29)/2 = 30  
map   (26+32)/2 = 28   (4+4)/2 = 4   (32+26)/2 = 28  
every   (22+24)/2 = 23   (4+5)/2 = 4.5   (41+45)/2 = 43  
$.each   (29+27)/2 = 28   (306+311)/2 = 308.5   (111+97)/2 = 104  
$(e).each   (94+98)/2 = 96   (484+488)/2 = 486   (79+64)/2 = 71.5  

数组长度为10^7

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wypdpf.html