JS 中八种遍历方法的执行速度

参考:https://www.jb51.net/article/112064.htm

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

运行速度大致排序为(8个常用函数):

1. fordo while
2. forEach、map、every  (3个不相上下,可认为运行速度差不多)
3. $.each
4. $(e).each
5. for in

执行速率测试代码:

var array = [],
 length = array.length = 10000000;//(一千万)
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));

分析总结

通过比较:根据统计数据, 可得这8个方法的运行速度大致排序为:

  1. for 与 do while
  2. forEach、map、every (这3个不相上下,可认为运行速度差不多)
  3. $.each
  4. $(e).each
  5. for in
posted @ 2022-12-06 22:19  轻风细雨_林木木  阅读(190)  评论(0编辑  收藏  举报