window.top.tests = {control:[], concat:[], spread:[], pushApply: []};
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.push(window.test);
if (window.top.tests.spread.length > window.cutoff) { window.top.tests.spread = []; console.log('reset spread'); }
Array.prototype.push.apply(window.top.tests.pushApply, window.test)
if (window.top.tests.pushApply.length > window.cutoff) { window.top.tests.pushApply = []; console.log('pushApply spread'); }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Control (for push) | |
Concat | |
Spread | |
PrototypePushApply |
Test name | Executions per second |
---|---|
Control (for push) | 173997.3 Ops/sec |
Concat | 385283.6 Ops/sec |
Spread | 766986.5 Ops/sec |
PrototypePushApply | 693437.1 Ops/sec |
Measuring performance differences in JavaScript can be fascinating, and BenchmarkThat.net is a great tool for comparing various approaches.
The provided JSON represents a benchmark test that compares four different methods to append elements to an array:
Control (for push)
: Uses the push()
method directly on the control
array.Concat
: Uses the concat()
method to concatenate new elements to the end of the concat
array.Spread
: Uses the spread operator (...
) to append new elements to the end of the spread
array.PrototypePushApply
: Uses the push.apply()
method, which is a prototype-based method that applies an array function to all elements of an array.Let's dive into each option:
Control (for push)
control
array. However, this might lead to unnecessary re-arrangements of the original array.Concat
concat()
method, which is optimized for performance.concat()
for performance.Spread
PrototypePushApply
push.apply()
method, which is optimized for performance.pushApply
array using push.apply()
. It's efficient because it avoids re-arranging the original array.Regarding special JavaScript features, the spread operator
(...
) is a relatively recent addition to JavaScript (ES6+) and might not be supported in older browsers or environments. However, most modern browsers support ES6+ features.
Other alternatives
If you want to compare more approaches, you could also consider using:
Array.prototype.slice()
: Creates a shallow copy of the original array.Array.prototype.unshift()
: Adds elements to the beginning of the array.Array.prototype.splice()
: Removes or replaces elements in the array.However, for this specific benchmark test, the four options provided are sufficient to compare the performance differences between different approaches.