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() | |
Array.from() | |
[...Array()] |
Test name | Executions per second |
---|---|
new Array() | 226192.2 Ops/sec |
Array.from() | 59619.7 Ops/sec |
[...Array()] | 222028.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
The provided JSON represents a benchmark test case on MeasureThat.net, which compares three approaches for creating filled arrays: new Array()
, Array.from()
and [...Array()]
.
Options being compared:
new Array()
: Creates an empty array and then fills it with the specified number of elements using the fill()
method.Array.from()
: Creates a new array from an existing iterable (in this case, an array) by providing a mapping function to transform each element.[...Array()]
: Creates a new array by spreading an empty array and then filling it with the specified number of elements.Pros and Cons:
new Array()
:fill()
.Array.from()
:new Array()
for large arrays, since it avoids creating an intermediate array.[...Array()]
:new Array()
.Library usage:
None of the options explicitly use any libraries, but they do rely on built-in JavaScript features like Array.prototype.fill()
and array spread syntax ([...array]
).
Special JS feature/syntax:
The benchmark test case uses a few special JavaScript features:
mapfn
variable is defined as an arrow function, which is a concise way to define small anonymous functions.var mapfn = (_, index) => {\r\n return index * 2 % 10;\r\n}
line uses template literals to create a multiline string.Other alternatives:
If you need to compare the performance of other array creation methods, some alternatives could be:
Array.from()
with map()
: Creating an empty array and then using map()
to fill it.Array.prototype.slice()
: Using slice()
to create a shallow copy of an existing array and then filling it with new elements.Uint8Array()
or Int32Array()
: Using typed arrays to create arrays optimized for specific data types.These alternatives might have different performance characteristics depending on the specific use case and requirements.