var params = [ "hello", true, 7 ]
var other = params.concat(1);
var params = [ "hello", true, 7 ]
var other = [ params, 1]
var other = [ "hello", true, 7 ]
other.push(1)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 4125997.0 Ops/sec |
spread operator | 5019329.5 Ops/sec |
push | 30247852.0 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Definition
The benchmark is comparing three approaches for concatenating arrays:
Array.prototype.concat()
[ ...params, 1]
)push()
method to add an element to the end of the array (other.push(1)
)Options Compared
The benchmark is comparing two main options:
Array.prototype.concat()
: a traditional way of concatenating arrays using the concat()
method.[ ...params, 1]
): a concise and modern way of creating a new array by spreading elements from an existing array.Pros and Cons
Here are some pros and cons of each approach:
[ ...params, 1]
):concat()
, concise syntax.Library
None of the benchmarked methods use a third-party library. The focus is on comparing the performance of these built-in JavaScript features.
Special JS Feature or Syntax
The ES6 spread operator ([ ...params, 1]
) is a new feature introduced in ECMAScript 2015 (ES6). It's not widely supported in older browsers or JavaScript engines.
Other Alternatives
If you're interested in exploring other approaches to concatenating arrays, some alternatives include:
Array.prototype.push()
method with two arguments (other.push(1)
): this is similar to using concat()
, but can be slightly faster.Array.from()
method: new Array(3).fill().map(() => ({ value: params[0] }, 1, true)).flat(1, Infinity).push(1)
Keep in mind that these alternatives may have different performance characteristics and are not as concise as the spread operator.
Overall, this benchmark provides a simple and controlled comparison of three common approaches to concatenating arrays in JavaScript.