var results = {concat: [], spread: [], push: []}
var params = Array.from({length: 10}, () => Math.floor(Math.random() * 10))
results.concat = results.concat.concat(params)
results.spread = [results.spread, params]
results.push.push(params)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator | |
Push |
Test name | Executions per second |
---|---|
Array.prototype.concat | 1276.0 Ops/sec |
spread operator | 874.4 Ops/sec |
Push | 1305515.9 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of three approaches to append an array to another array:
Array.prototype.concat()
: The traditional method of concatenating arrays using the concat()
method....
): The new ES6 spread operator, introduced in ECMAScript 2015, which allows for more concise and expressive array creation.push()
method with spread syntax (...
): A variation of the push()
method that uses the spread operator to append elements.Options Compared
The benchmark tests each approach on a large dataset (10 random integers) and measures their performance in terms of executions per second.
Pros and Cons of Each Approach:
Array.prototype.concat()
:...
):push()
method with spread syntax (...
):push()
methodLibrary and Purpose
None of the libraries are explicitly mentioned in the benchmark configuration. However, it's worth noting that the spread operator relies on the Array.prototype
prototype chain, which is a fundamental aspect of JavaScript.
Special JS Features or Syntax
The benchmark uses ES6 features such as:
...
): A new syntax introduced in ECMAScript 2015 for creating arrays and objects.\r\n
): Used to create multiline strings.These features are widely supported across modern browsers, but may not work as expected in older environments.
Alternatives
Other alternatives for appending arrays could include:
Array.prototype.splice()
: Instead of concatenating or pushing new elements, you can use splice()
to replace an existing element with a new array.concat
and push
.Keep in mind that these alternatives may have their own trade-offs in terms of performance, readability, and compatibility.