window.top.tests = {control:[], concat:[], spread:[]};
window.test = (new Array(10)).fill(null);
window.cutoff = 5000;
for (let element of window.test) window.top.tests.control.push(element);
window.top.tests.concat = window.top.tests.concat.concat(window.test);
window.top.tests.spread.push(window.test);
window.top.tests.spread = [window.top.tests.spread, window.test];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Control (for push) | |
Concat | |
Spread | |
Spread 2 |
Test name | Executions per second |
---|---|
Control (for push) | 414745.2 Ops/sec |
Concat | 744.3 Ops/sec |
Spread | 1555968.0 Ops/sec |
Spread 2 | 53699.5 Ops/sec |
The benchmark described compares the performance of different methods for appending elements to an array in JavaScript, specifically focusing on a large array. The methods being evaluated include traditional array push with a loop, array concatenation using the concat
method, and the spread operator for array operations.
Control (for push):
window.test
array using a for..of
loop and the push
method.Concat:
concat
to combine the existing array with window.test
in a way that effectively creates a new array.concat
can become expensive as array sizes grow.Spread:
...
) to efficiently append elements of window.test
to window.top.tests.spread
.Spread 2:
window.top.tests.spread
.According to the benchmark results:
While the benchmark focuses on these methods, there are other alternatives to manipulate arrays in JavaScript:
Array.prototype.unshift(): Adds elements to the beginning of an array. It could be interesting to measure how this compares to the other methods.
Array.prototype.splice(): Allows inserting elements at any position in the array but is typically slower due to it having to shift array elements.
Using Typed Arrays: Typed arrays may offer better performance for numerical data, but they lack the flexibility of regular arrays.
Dedicated libraries (e.g., Lodash): Libraries like Lodash offer utility functions for manipulating collections and arrays, potentially offering additional performance optimizations.
Ultimately, the choice of array manipulation method can depend heavily on context: the size of the data, frequency of operations, and whether the array's original order or content matters to the implementation.