const arr = [1,2];
arr.push(3);
let arr = [1,2];
arr = [arr, 3];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.push() | |
spread operator |
Test name | Executions per second |
---|---|
.push() | 91445056.0 Ops/sec |
spread operator | 55066828.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Definition The benchmark is defined as "Array .push() vs spread operator". This means that the benchmark compares the performance of two different approaches:
.push()
method to add an element to an array....
) to create a new array with the original elements and the newly added element.Options Compared
The two options being compared are:
.push()
: The push()
method is a built-in JavaScript method that adds one or more elements to the end of an array....
): The spread operator is used to create a new array by copying elements from an existing array. In this case, it's used to add a single element to the original array.Pros and Cons
.push()
: Pros:...
): Pros:.push()
for small arrays since it creates a new array with the newly added element, which can lead to less memory allocation and copying.
Cons:Library and Syntax Considerations
There is no library being used in this benchmark. The only syntax-related consideration is the use of the const
keyword for variable declarations, which is a feature introduced in ECMAScript 2015 (ES6). However, since both test cases are using modern JavaScript syntax, this shouldn't be an issue.
Other Alternatives
If you wanted to compare other approaches for adding elements to an array, you could consider:
unshift()
method instead of .push()
.assignIn
function.For example, an additional test case could compare the performance of .push()
versus creating a new array using the spread operator:
{
"Benchmark Definition": "let arr = [1,2];\r\nconst newArr = [...arr, 3];",
"Test Name": ".unshift() vs array creation"
}
This would allow you to compare the performance of .push()
versus creating a new array using the spread operator.