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);
if (window.top.tests.control.length > window.cutoff) { window.top.tests.control = []; console.log('reset control'); }
window.top.tests.concat = window.top.tests.concat.concat(window.test);
if (window.top.tests.concat.length > window.cutoff) { window.top.tests.concat = []; console.log('reset concat'); }
window.top.tests.spread = [window.top.tests.spread, window.test];
if (window.top.tests.spread.length > window.cutoff) { window.top.tests.spread = []; console.log('reset spread'); }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Control (for push) | |
Concat | |
Spread |
Test name | Executions per second |
---|---|
Control (for push) | 419019.4 Ops/sec |
Concat | 746384.9 Ops/sec |
Spread | 415994.6 Ops/sec |
Overview
The provided benchmark, hosted on MeasureThat.net, compares three approaches for appending elements to a large array in JavaScript: push()
, concat()
, and the spread operator (...
). The test aims to determine which approach is faster and more efficient.
Options Compared
push()
: This method modifies the array by adding one or more elements to the end of it.concat()
: This method returns a new array that contains all elements from the original array, followed by the elements passed as an argument (in this case, window.test
)....
): This operator creates a new array with the elements of the original array and the elements passed as an argument.Pros and Cons
push()
:concat()
:push()
, as it creates a new array and copies all elements from the original array....
):push()
due to the overhead of creating a new array.Library Usage
None of the test cases use external libraries, which is good for isolating the JavaScript engine's behavior and reducing potential interference from library-side optimizations or invariants.
Special JS Features/Syntax
The test does not utilize any special JavaScript features or syntax beyond what is necessary to demonstrate the three approaches. If additional features were used, it would require more context about their implementation and how they affect performance.
Alternative Approaches
push()
or concat()
, it can be used as an alternative way to append elements to an array.reduce()
, this method creates a new array with the results of applying a provided function to each element in the original array. Again, not directly comparable to push()
or concat()
.Keep in mind that these alternative approaches have different use cases and performance characteristics compared to push()
, concat()
, and the spread operator.