new Array(500).fill({})
Array.from({ length: 500 })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Array() | |
Array.from() |
Test name | Executions per second |
---|---|
new Array() | 1513528.4 Ops/sec |
Array.from() | 78294.6 Ops/sec |
Let's dive into explaining the benchmark.
What is tested:
The provided benchmark compares two approaches to create filled arrays in JavaScript:
new Array()
: This method creates an empty array and then fills it with a specified value using the fill()
method.Array.from()
: This method creates a new array from an iterable (in this case, an object) and fills it with a specified value.Options compared:
The benchmark compares the performance of these two approaches:
new Array()
with new Array(500).fill({})
as the test case for creating filled arrays.Array.from()
with Array.from({ length: 500 })
as the test case for creating filled arrays.Pros and Cons:
new Array()
:Array.from()
:new Array()
due to the optimized implementation.Array.from()
method, which may not be familiar to all developers.Library and purpose:
Array.from()
is a built-in JavaScript method introduced in ECMAScript 2015 (ES6). Its purpose is to create a new array from an iterable source, such as an object or an array. In this benchmark, Array.from()
is used to create a new array with a specified length and filled value.
Special JS feature:
The benchmark uses the fill()
method, which is not a special JavaScript feature per se, but rather a part of the language that allows arrays to be filled with a specific value. However, some developers might be familiar with it as an optimization technique for creating large arrays.
Other considerations:
new Array()
and Array.from()
when creating filled arrays. It does not account for other use cases where these methods are used.Alternatives:
Other alternatives to create filled arrays include:
const arr = [];
for (let i = 0; i < 500; i++) {
arr.push({});
}
Array.from()
method with an empty object as the iterable source, like this:const arr = Array.from({ length: 500 }, () => {});
These alternatives may have different performance characteristics and trade-offs compared to new Array()
and Array.from()
.