[removed] Difference between .forEach() and .map()

后端 未结 12 2023
余生分开走
余生分开走 2020-11-22 15:19

I know that there were a lot of topics like this. And I know the basics: .forEach() operates on original array and .map() on the new one.

I

12条回答
  •  深忆病人
    2020-11-22 15:39

    Performance Analysis For loops performs faster than map or foreach as number of elements in a array increases.

    let array = [];
    for (var i = 0; i < 20000000; i++) {
      array.push(i)
    }
    
    console.time('map');
    array.map(num => {
      return num * 4;
    });
    console.timeEnd('map');
    
    
    console.time('forEach');
    array.forEach((num, index) => {
      return array[index] = num * 4;
    });
    console.timeEnd('forEach');
    
    console.time('for');
    for (i = 0; i < array.length; i++) {
      array[i] = array[i] * 2;
    
    }
    console.timeEnd('for');
    

提交回复
热议问题