const base = [1];
const added = [1, 2, 3];
const combined = Array.prototype.push.apply(base, added);
const base = [1];
const added = [1, 2, 3];
const combined = base.push(added);
const base = [1];
const added = [1, 2, 3];
const combined = base.concat(added);
const base = [1];
const added = [1, 2, 3];
const combined = [base, added];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.push apply | |
array.push spread | |
array.concat | |
spread operator |
Test name | Executions per second |
---|---|
Array.prototype.push apply | 7671801.0 Ops/sec |
array.push spread | 43792676.0 Ops/sec |
array.concat | 9355765.0 Ops/sec |
spread operator | 28985338.0 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition:
The benchmark is designed to measure the performance of different ways to merge two arrays in JavaScript. The merged array will have elements from both the original arrays, base
and added
.
Script Preparation Code: There is no script preparation code provided for the benchmark, which means that the test cases are self-contained and don't rely on any external functions or variables.
Test Cases:
The benchmark consists of four test cases, each testing a different approach to merge the two arrays:
apply()
method to invoke push()
with an array of elements. The base
and added
arrays are merged in a single operation....
) to merge the two arrays into a new array.concat()
method to merge the two arrays into a new array....
) to merge the two arrays into a new array.Pros and Cons of Each Approach:
apply()
.push.apply()
or spread operator for very large arrays.Library/Functionality Used:
None of these test cases rely on any external libraries or functions beyond the built-in JavaScript features mentioned above.
Special JS Feature/Syntax:
The spread operator (...
) is a relatively recent addition to JavaScript, introduced in ECMAScript 2015. It allows for concise and expressive array merging and other operations.
Other Alternatives:
Some alternative approaches to merge two arrays include:
Array.prototype.slice()
to create a new array with elements from both original arrays.Array.prototype.reduce()
to build a new array by combining elements from both original arrays.Keep in mind that these alternative approaches may not be as efficient or concise as the methods tested in this benchmark.