let a = [];
for (let i = 0; i < 1000; i += 1) {
const values = [i, 10000 + i, 100000 + i];
values.forEach(value => {
a.push(value);
});
}
let a = [];
for (let i = 0; i < 1000; i += 1) {
const values = [i, 10000 + i, 100000 + i];
Array.prototype.push.apply(a, values);
}
let a = [];
for (let i = 0; i < 1000; i += 1) {
const values = [i, 10000 + i, 100000 + i];
a.push(values);
}
let a = [];
for (let i = 0; i < 1000; i += 1) {
const values = [i, 10000 + i, 100000 + i];
a = [a, values];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
push | |
push.apply | |
push spread | |
reassign spread |
Test name | Executions per second |
---|---|
push | 63342.6 Ops/sec |
push.apply | 7093.2 Ops/sec |
push spread | 70863.2 Ops/sec |
reassign spread | 620.2 Ops/sec |
I'll explain the benchmark in detail.
Overview
The provided JSON represents a JavaScript microbenchmark test case named "push vs apply.push vs spread". The test compares the performance of three different approaches to push elements onto an array:
push
method directly on the array.apply
method with Array.prototype.push
....
) to create a new array and then reassigning it to the original array.Options Compared
The three options being compared are:
push
method directly on the array, e.g., a.push(value);
.Array.prototype.push.apply(a, values)
, where values
is an array of elements to be pushed onto a
....
) to create a new array and then reassigning it to the original array, e.g., a = [...a, ...values];
.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Library and Special JS Features
None of the test cases use any external libraries or special JavaScript features (e.g., ES6 classes, async/await).
Benchmark Results
The latest benchmark results show that the "push spread" approach outperforms the other two options, followed closely by "apply with push". The results suggest that using the spread operator and reassigning can be an efficient way to add elements to an array without modifying its original state.
Other Alternatives
Some alternative approaches to pushing elements onto an array include:
unshift
instead of push
.a[i++] = value;
).concat
to concatenate arrays (although this is generally less efficient than the spread operator).However, these alternatives are not part of the provided benchmark test case, and their performance characteristics may vary depending on specific use cases and JavaScript engines.