var mapfn = (_, index) => {
return index * 2 % 10;
}
new Array(500).fill(500).map(mapfn)
Array.from({ length: 500 }, mapfn)
[Array(500)].map(mapfn)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Array().fill() | |
Array.from() | |
[...Array()] |
Test name | Executions per second |
---|---|
new Array().fill() | 264840.1 Ops/sec |
Array.from() | 68000.0 Ops/sec |
[...Array()] | 243047.4 Ops/sec |
Let's dive into the explanation of the provided JSON benchmark.
Benchmark Definition
The benchmark tests the performance difference between three ways to create filled arrays in JavaScript: new Array().fill()
, Array.from()
with an array constructor, and [...Array()]
(the spread operator).
Options being compared
new Array().fill()
: This method creates a new array with a specified number of elements, all set to the same value. In this case, it's used to create an array of 500 elements filled with the value 500
.Array.from()
with an array constructor: This method creates a new array from an iterable or an array-like object. Here, it's used to create an array from an array constructor that generates 500 elements.[...Array()]
(spread operator): This is the spread operator, which converts an array into an array of its elements.Pros and Cons
new Array().fill()
:Array.from()
with an array constructor:new Array().fill()
as it avoids the overhead of creating a new array.[...Array()]
(spread operator):Library/Function Used
In this benchmark, the mapfn
function is used as a callback function. It takes two arguments: _
(the map iteration argument) and index
. The function returns an index multiplied by 2, modulo 10 (index * 2 % 10
). This function is used to calculate some intermediate value that's likely not relevant to the performance test.
Special JS Feature/Syntax
No special JavaScript features or syntax are used in this benchmark. It's a straightforward comparison of three array creation methods.
Other Alternatives
If you wanted to test other array creation methods, here are a few options:
Array.prototype.fill()
: This method creates a new array with a specified number of elements, all set to the same value.Array.from()
without an array constructor: You can also use Array.from()
with an iterable or an object as its argument.[...new Set()]
or [...new Map()]
.Keep in mind that the performance differences between these methods are usually minimal, and it's essential to consider the specific requirements of your application when choosing an array creation method.