for、forEach、map 有什么区别

速度上 for > forEach > map

for 循环时没有创建对象,节约了时间。
forEach 循环时创建 value 对象
map 循环时创建 value 对象,还要新建 Array 对象

var arr = Array(10000000).fill(0).map((v,i) => i)

function computeFor() {
  var start1 = new Date().getTime();
  for(var i = 0; i < arr.length;i ++) {
    arr[i] = i+1;
  }

  var stop1 = new Date().getTime();
  console.info("for: ",stop1 - start1);
}

function computeForEach() {
  var start2 = new Date().getTime();
  arr.forEach(function(value,index,array) {
    arr[index] = index+1;
  });

  var stop2 = new Date().getTime();
  console.info("forEach:",stop2-start2); 
}

function computeMap() {
  var start3 = new Date().getTime();
  arr.map(function(value,index,array) {
    arr[index] = index+1;
  });

  var stop3 = new Date().getTime();
  console.info("map:",stop3-start3);
}

function demo() {
    computeFor()
    computeForEach()
    computeMap()
}

demo();
posted @ 2022-03-10 09:56  远方的少年🐬  阅读(90)  评论(0编辑  收藏  举报