Skip to content

Instantly share code, notes, and snippets.

@oriverk
Created August 19, 2021 09:46
Show Gist options
  • Save oriverk/1db3654322e1dded7f3efab90b19e827 to your computer and use it in GitHub Desktop.
Save oriverk/1db3654322e1dded7f3efab90b19e827 to your computer and use it in GitHub Desktop.
JS: how to flatten 1000x1000 of 2-dimensional array; for.push vs reduce.concat vs spread syntax vs Array.prototype.push.apply(a, b)

enviroment

  • ubuntu 20.04LTS
    • RAM: 16GB
    • CPU: intel core i5 8t gen
  • node v14.17.2

for.push vs reduce.concat vs spread syntax vs Array.prototype.push.apply(a, b)

test codes

  
  const data = [];
for(let i=0;i<1000;i++){
  data[i]=[];
  for(let j=0;j<1000;j++){
    data[i][j]=i*10+j;
  }
}

console.time("method1:for.push");
for(var n=0;n<100;n++){
  var list1 = [];
  for(var i=0;i<data.length;i=i+1){
    for(var j=0;j<data[i].length;j=j+1){
      list1.push(data[i][j]);
    }
  }
}
console.timeEnd("method1:for.push");

console.time("method2:reduce.concat");
for(let n=0;n<100;n++){
  const list2 = data.reduce((pre,current) => {pre.push(...current);return pre},[]);
}
console.timeEnd("method2:reduce.concat");

console.time('method:2-1')
const list21 = data.reduce((pre,current) => {pre.push(...current);return pre},[]);
console.timeEnd('method:2-1')

console.time('method:2-2')
const list22 = data.reduce((pre, current) => [...pre, ...current], []);
console.timeEnd('method:2-2')

console.time('method:2-3')
const list23 = data.reduce((pre, current) => pre.concat(...current), []);
console.timeEnd('method:2-3')

console.time('method:3')
const list3 = [].concat(...data);
console.timeEnd('method:3')

console.time('method:3-2')
const list = []
Array.prototype.push.apply(list, ...data)
console.timeEnd('method:3-2')

results

  
method1:for.push: 2.241s
method2:reduce.concat: 2.294s
method:2-1: 26.764ms
method:2-2: 6.481s
method:2-3: 5.690s
method:3: 6.33ms
method:3-2: 0.021ms
  

使い分け的には,

方法3-1: メソッドチェーン使いたいとき 方法3-2: とにかく速さが必要なとき でしょうか.

重要:実際に使う時は・・・・https://qiita.com/kaz2ngt/items/6e08acc537fd77273cff#comment-842233322ea7caeb9aa0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment