var a = new Map();
for (let i=0;i<1000;i++) {
a.set('x'+i, {p:['a', 'b', 'c']});
}
const res = Array.from(a.values(), (val) => val.p).flat();
const b = [];
for (let v of a.values()) {
b.push(v.p);
}
const res = b.flat();
let res = [];
for (let v of a.values()) {
res = [res, v.p];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array from with map + flat | |
Array push + flat | |
spread |
Test name | Executions per second |
---|---|
Array from with map + flat | 925.7 Ops/sec |
Array push + flat | 995.5 Ops/sec |
spread | 306.3 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of three different approaches to flatten an array of arrays in JavaScript: Array.from()
, push()
+ flat()
, and spread operator (...
).
Benchmark Definition JSON Analysis
The benchmark definition JSON contains the following information:
a
with 1000 entries, where each entry has an array p
containing three elements. This script is used to prepare the data for the benchmark.Individual Test Cases
The individual test cases are defined as an array of objects, each containing:
a
using one of the three approaches.Breakdown of Test Cases
Here's a brief explanation of each test case:
Array.from()
and flat()
to flatten the array a
.push()
method to add elements to an array and then calls flat()
on that array....
) to flatten the array a
.Library Used
In this benchmark, no libraries are explicitly used.
Special JS Features or Syntax
The benchmark uses the following special JavaScript features:
Array.from()
: A method introduced in ECMAScript 2015 (ES6) that creates a new array from an iterable....
): Introduced in ECMAScript 2015 (ES6), this operator is used to expand an array into individual elements.Pros and Cons of Each Approach
Here's a brief pros and cons analysis for each approach:
push()
and can be optimized for small arrays.Array.from()
+ flat()
for larger arrays, as it involves multiple allocations and copies....
):Other Alternatives
If the spread operator is not an option due to browser limitations or other constraints, some alternative approaches can be used:
map()
to create a new array and then concatenating the results using concat()
.However, these alternatives may have different performance characteristics and are generally less efficient than the spread operator or Array.from()
+ flat()
.