var arr = [1, 2, 3, 4, 5]
var other = arr.concat(3);
var arr = [1, 2, 3, 4, 5]
var other = [ arr, 3 ]
var arr = [1, 2, 3, 4, 5]
var other = arr.push(3);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 4437041.0 Ops/sec |
spread operator | 30229826.0 Ops/sec |
Push | 47660772.0 Ops/sec |
Let's break down the test cases and explain what's being tested.
General Overview
The benchmark is comparing three different ways to add an element to an array in JavaScript: concat()
method, spread operator (...
), and push()
method.
Options Compared
concat()
method....
operator.push()
method to add a single element to the end of an array.Pros and Cons
concat()
methodLibrary and Special JS Features
None of the test cases use any external libraries. However, it's worth noting that the spread operator is a new feature introduced in ECMAScript 2018 (ES9), so it requires a compatible browser or transpiler to work.
Other Considerations
When choosing between these methods, consider the following factors:
push()
method might be the fastest option. For smaller arrays, the spread operator might be sufficient.concat()
.concat()
method.Alternatives
If you're looking for alternative ways to add an element to an array, consider using:
Array.prototype.splice()
: Replaces elements at a specified index with new elements and shifts other elements.Array.prototype.unshift()
: Adds one or more elements to the beginning of an array.Array.prototype.concat()
with Array.from()
: Creates a new array from an existing iterable (e.g., another array).Keep in mind that each method has its own trade-offs, so choose the one that best fits your specific use case.