Array.apply(null, Array(1000)).map((item, i) => {});
[Array(1000)].map((item, i) => {});
Array(1000).fill(null).map((item, i) => {});
Array.from({ length: 1000 }).map((item, i) => {});
Array.from({ length:1000 }, (item, i) => {});
const arr = []
for (let i = 0; i < 1000; ++i) arr.push({})
const arr = new Array(1000);
for (let i = 0; i < 1000; ++i) arr.push({})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.apply(null, Array(n)) | |
[...Array(n)] | |
Array(n).fill(null) | |
Array.from({ length: n }) | |
Array.from({ length:n }, (item, i) => i) | |
Array.push | |
Array with length + push |
Test name | Executions per second |
---|---|
Array.apply(null, Array(n)) | 245904.2 Ops/sec |
[...Array(n)] | 375066.8 Ops/sec |
Array(n).fill(null) | 386268.6 Ops/sec |
Array.from({ length: n }) | 40169.3 Ops/sec |
Array.from({ length:n }, (item, i) => i) | 34887.6 Ops/sec |
Array.push | 325620.8 Ops/sec |
Array with length + push | 262179.2 Ops/sec |
The benchmark defined in the provided JSON compares different methods of creating an array filled with empty objects (or a specific value) suitable for iteration in JavaScript. Each method is assessed by measuring how quickly it can perform the operation for an array of size 1,000.
Array.push
const arr = [];\nfor (let i = 0; i < 1000; ++i) arr.push({});
push
.Array with length + push
const arr = new Array(1000);\nfor (let i = 0; i < 1000; ++i) arr.push({});
push
.Array.apply
Array.apply(null, Array(1000)).map((item, i) => {});
apply
method on Array
, which can be concise for certain use cases.apply
has some overhead, and constructing an array this way can introduce complexity.Spread operator
[...Array(1000)].map((item, i) => {});
apply
, the spread operator can be slower in some cases, especially due to generating intermediate objects.Array.prototype.fill
Array(1000).fill(null).map((item, i) => {});
fill
is generally quick, creating filled arrays and then mapping over them can afford some overhead for large arrays.Array.from
Array.from({ length: 1000 }).map((item, i) => {});
Array.from({ length: 1000 }, (item, i) => i);
Array.from()
is a versatile method that can create an array from array-like or iterable objects. The second version allows for transforming directly during initialization.The benchmark results provide the number of executions per second for each method under the same environment:
Array(1000).fill(null)
with 386,268 executions/sec.[...Array(1000)]
at 375,066 executions/sec.Array.push
at 325,620 executions/sec, and so on.Array.from
, which falls behind the standard array creation methods.This ensures that developers have a comprehensive understanding of different practices for creating arrays in JavaScript and can select the best approach based on their performance requirements and code style preferences.