var collection = new Array(100);
collection.fill(6);
var value = 7;
var result = collection.concat(value);
var collection = new Array(100);
collection.fill(6);
var value = 7;
var result = [collection, value];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.concat | |
spread operator |
Test name | Executions per second |
---|---|
Array.prototype.concat | 1161609.1 Ops/sec |
spread operator | 892489.9 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The test compares two ways to add an element to an array in JavaScript: using the Array.prototype.concat()
method and the spread operator (...
). The benchmark is designed to measure which approach performs better for creating a new array with a single element.
Options Compared
There are two options being compared:
Array.prototype.concat()
: This method concatenates one or more arrays into a new array, appending all the elements from each argument in the same order....
): This operator is used to create a new array by spreading an existing array or value.Pros and Cons
Here are some pros and cons of each approach:
Array.prototype.concat()
:...
):Library Used
There is no specific library used in this benchmark. The Array.prototype.concat()
method is a built-in JavaScript method, while the spread operator (...
) is also part of the ECMAScript standard.
Special JS Feature/Syntax
The benchmark uses modern JavaScript features:
...
): introduced in ECMAScript 2018+.\r\n...
): used for multiline strings.Other Alternatives
For creating a new array with a single element, you can also use other methods like Array([element])
or simply assign the element to an empty array []
. However, these alternatives may not be as concise or efficient as using the spread operator (...
) or Array.prototype.concat()
.
Benchmark Preparation Code
The benchmark preparation code is intentionally left blank ("Script Preparation Code": null
, "Html Preparation Code": null
), which means that the test relies on the JavaScript engine's built-in behavior and does not require any additional setup or initialization.