var params = [5 , 8, 9 ];
var other = [ 1, 2 ].concat(params);
var params = [5 , 8, 9 ];
var other = [ 1, 2, params ]
var params = [5 , 8, 9 ];
var other = [ 1, 2 ].push(params);
var params = [5 , 8, 9 ];
var ar = [ 1, 2 ]
var other = ar.push.apply(ar, params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Push | |
Push w/apply |
Test name | Executions per second |
---|---|
Array.prototype.concat | 26255906.0 Ops/sec |
spread operator | 24996580.0 Ops/sec |
Push | 33238788.0 Ops/sec |
Push w/apply | 34691940.0 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark definition JSON and test case describe four different methods for concatenating or merging arrays: the traditional concat()
method, the new ES6 spread operator (...
), push
, and push.apply
. We will analyze each method, its pros and cons, and consider alternative approaches.
Benchmark Definition
The benchmark definition states that we want to compare:
Array.prototype.concat
...
)push
push.apply
Methods and their Pros/Cons:
Array.prototype.concat
concat([array1], [array2])
merges two arrays into a single array....
)var arr = [1, 2]; var other = [...arr, 3, 4];
push
array.push(element)
adds an element to the end of an array.push.apply
Array.prototype.push.apply(arr, [element1], [element2])
applies an array of elements to a target array using push
.push
, but with more flexibility.Library and Purpose
None of these methods rely on external libraries. However, if we were to use libraries like Lodash or Ramda for array manipulation, they might provide additional benefits or optimizations.
Special JS Feature/Syntax: ES6 Spread Operator
The new ES6 spread operator (...
) is a concise way to merge arrays. It was introduced in ECMAScript 2015 and has become widely adopted since then. Its performance benefits come from the fact that it avoids creating a new array object, instead modifying the existing one.
Alternative Approaches
Other methods for merging or concatenating arrays include:
Array.prototype.reduce()
with an initial value.[...array1, ...array2]
) and then assigning it to a variable.Array.prototype.concat()
followed by assignment.These alternatives may offer different performance benefits or trade-offs in terms of readability. However, they are generally less efficient than the methods described above.
Conclusion
Each method has its strengths and weaknesses. The choice between them ultimately depends on your specific use case, performance requirements, and personal preference. MeasureThat.net provides a useful platform for comparing these methods and determining their relative performance on different hardware configurations.