let array2D = [];
const n = 1000;
const c = 100;
for (let i = 0; i < n; i++) {
let array1D = [];
for (let k = 0; k < c; k++) {
array1D.push(k);
}
array2D.push(array1D);
}
window.array2D = array2D;
let result1 = [].concat(window.array2D);
let result = window.array2D.flat();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spreading + concat | |
Flat |
Test name | Executions per second |
---|---|
Spreading + concat | 5829.9 Ops/sec |
Flat | 81.5 Ops/sec |
Let's dive into the provided benchmarking data.
Benchmark Definition and Script Preparation Code
The benchmark is comparing two approaches to flatten a 2D array in JavaScript: using Array.prototype.concat()
with spreading (...
) and using the flat()
method.
The script preparation code creates a large 2D array array2D
with dimensions n x c
, where n = 1000
and c = 100
. This array is then assigned to the global scope (window.array2D
).
Options Compared
Two options are compared:
...
) to flatten the 2D array, followed by the concat()
method.flat()
method on the 2D array.Pros and Cons of Each Approach
flat()
, as it involves multiple steps (spreading, concatenation).flat()
method in older browsers, which may not be the case.Library and Purpose
In neither of the benchmarked test cases does the code use any additional libraries. However, if we were to extend the scope of the comparison, we'd likely encounter libraries like Lodash or Ramda, which provide utility functions for array manipulation, including flattening arrays.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes used in this benchmarking code. The focus is on comparing two basic approaches to flatten a 2D array.
Other Alternatives
Other alternatives to compare the performance of array flattening include:
Array.prototype.reduce()
to flatten the array.When preparing this benchmark, you would need to ensure that the script preparation code is executed in isolation, without any external dependencies or optimizations. The individual test cases should be run multiple times to capture representative results, taking care not to skew the output with variations in input data or system load.