window.top.tests = {control:[], concat:[], pushSpread: [], 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.pushSpread.push(window.test);
if (window.top.tests.pushSpread.length > window.cutoff) { window.top.tests.pushSpread = []; console.log('reset push spread'); }
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 | |
Push (with spread) | |
Spread |
Test name | Executions per second |
---|---|
Control (for push) | 115349.0 Ops/sec |
Concat | 105985.7 Ops/sec |
Push (with spread) | 453005.9 Ops/sec |
Spread | 24379.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The provided benchmark compares three different ways to append elements to a large array: push()
, concat()
, and the spread operator (...
). The goal is to determine which approach has the best performance for large arrays.
Options Compared
push()
method to add an element to the end of the array.concat()
method to create a new array and append the elements to it....
) to create a new array and append the elements to it.Pros and Cons
push()
or the spread operator.Array.prototype.push()
method under the hood.Library and Special JS Features
There are no libraries or special JS features used in this benchmark. However, it's worth noting that the spread operator is a relatively recent addition to JavaScript (introduced in ECMAScript 2018) and may not be supported by older browsers or versions of Node.js.
Other Considerations
When working with large arrays, consider the following:
push()
when you need to append elements to an existing array frequently....
) when you need to create a new array without creating intermediate arrays.concat()
.lodash
or underscore
, which provide optimized array methods for performance-critical applications.Alternative Benchmarking Approaches
MeasureThat.net offers other benchmarking approaches, such as:
Keep in mind that each benchmarking approach has its strengths and weaknesses, and the choice of approach depends on your specific use case and requirements.