new Array(500).fill(0, 0, 500)
Array.from({ length: 500 }, () => 0)
[Array(500)].map(() => 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
new Array() | |
Array.from() | |
new Array() + destruct |
Test name | Executions per second |
---|---|
new Array() | 907668.8 Ops/sec |
Array.from() | 33344.6 Ops/sec |
new Array() + destruct | 419879.6 Ops/sec |
Let's break down what's being tested in the provided benchmark.
The goal of this benchmark is to compare the performance of three different approaches for creating filled arrays:
new Array()
: This approach creates an empty array and then uses the fill()
method to fill it with a specified number of elements.Array.from()
: This approach uses the from
function to create a new array from an iterable, such as an array literal or an object with a length
property.new Array() + destruct
: This approach creates a filled array using the new Array()
constructor and then uses destructuring syntax to extract individual elements.Now, let's discuss the pros and cons of each approach:
1. new Array()
Pros:
Cons:
fill()
method, which can create a new array in some browsers2. Array.from()
Pros:
new Array()
approachCons:
3. new Array() + destruct
Pros:
Cons:
Now, let's talk about the libraries used in this benchmark. The Array.from()
function is part of the modern JavaScript standard library (ECMAScript 2015+). If you're using an older browser or environment that doesn't support ES6+, you may need to use a polyfill or compatibility layer to access this method.
The "new Array() + destruct" approach uses modern array features like destructuring and spread operators, which are also part of the modern JavaScript standard library. However, some browsers may not implement these features correctly or at all.
Other alternatives for creating filled arrays include:
Buffer
object with the fill()
method (available in Node.js and some browser engines)repeat()
function (not shown in this benchmark)Keep in mind that the performance differences between these approaches can be significant, depending on the specific use case and browser environment.