var arr = ['hello', true, 7];
arr.push(1);
var arr = ['hello', true, 7];
arr = [arr, 1];
var arr = ['hello', true, 7];
arr.push(1);
arr.push(2);
arr.push(3);
var arr = ['hello', true, 7];
arr = [arr, 1, 2, 3];
var arr = ['hello', true, 7];
Array.prototype.push.apply(arr, [1, 2, 3]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.push | |
spread operator | |
Array.prototype.push multiple | |
spread operator multiple | |
Array.prototype.push.apply |
Test name | Executions per second |
---|---|
Array.prototype.push | 52061640.0 Ops/sec |
spread operator | 29609108.0 Ops/sec |
Array.prototype.push multiple | 51852296.0 Ops/sec |
spread operator multiple | 26545592.0 Ops/sec |
Array.prototype.push.apply | 6247772.0 Ops/sec |
Measuring the performance of different JavaScript methods for adding elements to an array can be interesting.
What is being tested?
The benchmark tests four ways to add elements to an array:
Array.prototype.push
: The traditional method of adding a single element to an array using the push()
method.arr = [...arr, 1]
): A new ES6 feature that allows creating a new array by spreading the elements of an existing array and adding new elements.Array.prototype.push() multiple
: Adding multiple elements to an array using push()
.Array.prototype.push.apply()
: Using the apply()
method to add multiple elements to an array.Options compared
The benchmark compares the performance of these four methods on an initial array with three elements (['hello', true, 7']
). The tests aim to measure which method is faster and more efficient.
Pros and cons of each approach:
Array.prototype.push
:arr = [...arr, 1]
):push()
for small arrays.Array.prototype.push() multiple
:Array.prototype.push.apply()
:Library and purpose
None mentioned in this benchmark definition.
No special JavaScript features or syntax are used in this benchmark.
Other alternatives
If you want to test more methods or explore alternative approaches, you can consider:
splice()
, unshift()
, or concat()
.Keep in mind that these alternatives will require additional benchmarking effort and consideration of potential factors affecting performance.