var params = [ "hello", true, 7 ];
var existingArray = [1, 2];
var other = existingArray.concat(params);
var other = [ existingArray, params ]
var other = existingArray.push(params);
var other = params.forEach(function (item) {
existingArray.push(item);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
Multiple spread | |
Push spread | |
Multiple push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 3034228.8 Ops/sec |
Multiple spread | 4660026.0 Ops/sec |
Push spread | 3689602.5 Ops/sec |
Multiple push | 2217334.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and analyzed.
Benchmark Overview
The benchmark compares the performance of three approaches to concatenate arrays in JavaScript:
Array.prototype.concat()
...
)push(...)
)Library Used: None
This benchmark does not rely on any external libraries, making it a vanilla JavaScript test.
Special JS Feature/Syntax
The spread operator and the spread push method were introduced in ECMAScript 2015 (ES6). They provide a concise way to create new arrays by spreading existing ones or pushing elements onto an array.
Benchmark Test Cases
Each test case measures the performance of one specific approach. The test cases are:
Array.prototype.concat()
: Concatenates two arrays using the traditional method.Multiple spread
([ ...existingArray, ...params ]
): Creates a new array by spreading both existing and new arrays.Push spread
(existingArray.push(...params)
): Pushes elements onto an existing array using the spread operator.Multiple push
: Iterates over the new array and pushes each element onto the existing array.Comparison
The benchmark compares these four approaches to measure their performance differences:
Pros and Cons
Here's a brief overview of each approach:
Array.prototype.concat()
:[ ...existingArray, ...params ]
):existingArray.push(...params)
):Results
The latest benchmark results show that:
Multiple spread
outperforms all other approaches, with an average of 4.66 executions per second on a Chrome 70 browser running on a Mac OS X 10.13.6 machine.Push spread
follows closely behind, averaging around 3.03 executions per second.Alternatives
Other alternatives for concatenating or modifying arrays include:
Array.from()
method to create a new array from an iterable source.Keep in mind that these alternatives may come with additional dependencies, complexity, and performance trade-offs.