最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Performance of Array.flat() vs spread operator to flatten multiple arrays into one - Stack Overflow

programmeradmin4浏览0评论

Which is a better and more efficient way to flatten multiple arrays into one?

Spread operator:

let arr = [];
for (const array of arrays) {
  arr.push(…array);
}

Or with .flat():

let arr = [];
for (const array of arrays) {
  arr.push(array);
}
arr = arr.flat();

I am using a loop instead of just const arr = arrays.flat() because I want to test something very specific.

Which is a better and more efficient way to flatten multiple arrays into one?

Spread operator:

let arr = [];
for (const array of arrays) {
  arr.push(…array);
}

Or with .flat():

let arr = [];
for (const array of arrays) {
  arr.push(array);
}
arr = arr.flat();

I am using a loop instead of just const arr = arrays.flat() because I want to test something very specific.

Share Improve this question edited Aug 29, 2023 at 16:24 Darryl Noakes 2,8101 gold badge14 silver badges30 bronze badges asked Jul 11, 2021 at 20:26 Maor agaiMaor agai 3411 gold badge7 silver badges16 bronze badges 7
  • You have to test it, but I guess .flat() is more efficient as it's implemented by the browser, thus written in C/C++ and better optimized. – Guerric P Commented Jul 11, 2021 at 20:29
  • 1 why not just const arr = arrays.flat()? No need for your loop (which should be lowercase for). – pilchard Commented Jul 11, 2021 at 20:34
  • @plichard l’m from mobile, that’s why I got “for” with upper case.. And I wanted to test something very specific, that’s why I want it with for loop. – Maor agai Commented Jul 11, 2021 at 20:42
  • ... spreads one level only. It has a different purpose from Array.prototype.flat – Aluan Haddad Commented Jul 11, 2021 at 20:48
  • 1 flat flattens to arbitrary depth. ... does does something pletely different. Performance is irrelevant when paring operations that are not analogous – Aluan Haddad Commented Jul 11, 2021 at 20:49
 |  Show 2 more ments

2 Answers 2

Reset to default 8

If you need single-level flattening, according to this JSBench I cooked up,

let arr = [].concat(...arrays);

is by far the fastest (on my Windows Chrome 93, according to ments not so on Safari), more than 3x the speed of your implementation.

Running the same bench as the accepted answer, that solution is faster than the others tested, but I tested a couple of others and found another solution that is around ~12% faster:

let arr = [].concat.apply([], arrays);

Benchmark testing: https://jsbench.me/adlib26t2y/2

发布评论

评论列表(0)

  1. 暂无评论