var params = [ "hello", true, 7 ];
var other = [ 1, 2 ].push(params);
var params = [ "hello", true, 7 ];
var other = [ 1, 2 ].concat(params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.push( spread ) | |
Array.concat() |
Test name | Executions per second |
---|---|
Array.push( spread ) | 27929518.0 Ops/sec |
Array.concat() | 5212591.5 Ops/sec |
Let's dive into what this benchmark tests and what it means for software engineers.
What is being tested?
This benchmark compares the performance of two different approaches to add elements to an existing array in JavaScript:
Array.push(...params)
: This uses the spread operator (...
) to expand an array-like object params
into a comma-separated list, which is then passed as arguments to the push()
method.Array.concat(params)
: This directly concatenates another array (or array-like object) params
with an existing array using the concat()
method.What options are being compared?
In this benchmark, two test cases are compared:
...
) to add elements from params
to an existing array [1, 2]
, resulting in a new array with all elements.params
array with an existing array using concat()
.Pros and cons of each approach:
Array.push(...params)
: This approach is more concise and readable when adding multiple elements to an existing array. However, it can be slower than concat()
for large arrays, as each push()
operation creates a new array and copies the old contents.Array.concat(params)
: This approach is generally faster than push()
for large arrays, as it uses a single concat()
method to create a new array with all elements. However, it can be less readable when adding multiple elements.Other considerations:
push()
might be slightly faster than concat()
.push()
and concat()
is relatively small, but push()
might still have a slight advantage for large arrays.Library usage:
None in this benchmark. The test cases only use built-in JavaScript methods (Array.push()
, Array.concat()
) and operators (...
spread operator).
Special JS features or syntax:
The benchmark uses the spread operator (...
) to expand an array-like object into a comma-separated list.
Other alternatives:
While not tested in this specific benchmark, alternative approaches exist:
push()
method with each element as separate arguments: other.push('hello').push(true).push(7)
.Set
data structure to add unique elements to an existing array.These alternatives might be worth exploring depending on specific use cases and performance requirements.