var params = [ "hello", true, 7 ];
var other = [params, {id: 123} ]
var other = [ 1, 2 ].push({id: 123});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread operator | |
Push |
Test name | Executions per second |
---|---|
spread operator | 21350120.0 Ops/sec |
Push | 35590408.0 Ops/sec |
Let's dive into the provided benchmark and explain what's being tested.
What is being tested?
The benchmark compares two approaches to concatenate arrays:
...
): Introduced in ES6, this operator allows you to expand an array or other iterable by its elements.concat()
method: A built-in JavaScript function that combines two or more arrays.Options compared
Two test cases are used to compare the performance of these two approaches:
"spread operator"
): Creates an array params
with three elements and then uses the spread operator (...
) to add another object with an id
property."Push"
): Creates an array [1, 2]
, pushes a new object with an id
property onto it using the push()
method.Pros and Cons of each approach
Spread Operator (...
)
Pros:
Cons:
concat()
due to the overhead of creating a new array.Traditional concat()
method
Pros:
Cons:
Other considerations
Library usage
There are no libraries mentioned in this benchmark, so we don't have any external dependencies affecting the test results.
Special JS features or syntax
The spread operator (...
) is a modern JavaScript feature introduced in ES6. It allows you to expand an array or other iterable by its elements. This feature is widely supported in modern browsers and engines, but older versions might not execute it correctly.
Alternatives
Other alternatives for concatenating arrays include:
Array.prototype.concat()
: A built-in method that combines two or more arrays.array.push(element1); array.push(element2);