const length = 100000
function arrayFrom() {
const array = Array.from({length: length}, x => x = true)
}
function arrayLoop() {
const array = [];
for (let i = 0; i < length; i++) array.push(true);
}
function arrayFill() {
const array = Array(length).fill(true);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array from | |
Array loop | |
Array(length).fill |
Test name | Executions per second |
---|---|
Array from | 49608240.0 Ops/sec |
Array loop | 52680016.0 Ops/sec |
Array(length).fill | 52236356.0 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of three different ways to create an array in JavaScript: Array.from()
, using a traditional for
loop (arrayLoop()
), and using the Array(length).fill(true)
syntax.
Script Preparation Code
The script preparation code sets the length of the array to be created, which is 100,000. This value is used consistently across all three benchmark definitions.
Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark results are likely being generated in a headless browser environment (e.g., Chrome Headless).
Individual Test Cases
The individual test cases are defined as follows:
function arrayFrom() {
const array = Array.from({length: length}, x => x = true);
}
This code uses the Array.from()
method to create an array with the specified length. The callback function x => x = true
is used to initialize each element of the array.
function arrayLoop() {
const array = [];
for (let i = 0; i < length; i++) array.push(true);
}
This code uses a traditional for
loop to create an array with the specified length. The push()
method is used to add each element to the array.
function arrayFill() {
const array = Array(length).fill(true);
}
This code uses the Array(length)
constructor and the fill()
method to create an array with the specified length, filled with a value of true
.
Pros and Cons
Here are some pros and cons of each approach:
Array.from()
true
)Array(length)
Library and Special JS Features
There are no libraries mentioned in this benchmark. However, some browsers may have special JavaScript features or extensions enabled (e.g., WebAssembly, GPU acceleration), which could potentially impact performance.
Other Alternatives
Some alternative ways to create an array in JavaScript include:
Array()
constructor with a variable lengthconst array = new Array(length);
Array.prototype.fill()
method (which is similar to Array(length).fill()
)const array = [];
array.length = length;
array.fill(true);
It's worth noting that the choice of array creation method depends on the specific requirements and constraints of your application.