let n = 10000, length = 50;
const result = [];
for (let i = 0; i < n; ++i) {
result.push(Array.from({length}, _ => length));
}
let n = 10000, length = 50;
const result = [];
for (let i = 0; i < n; ++i) {
result.push(Array(length).fill(length));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
from | |
fill |
Test name | Executions per second |
---|---|
from | 38.2 Ops/sec |
fill | 415.3 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare two approaches for creating arrays of repeated values: using Array.from()
with a callback function (_ => length
) versus using Array(length).fill(length)
.
Approaches Compared
Array.from()
with a callback function: This approach uses the Array.from()
method, which takes an array-like object and converts it into a new array. The callback function _ => length
is applied to each element of the resulting array, effectively repeating the value length
.Array(length).fill(length)
: This approach creates a new array with length
elements and then fills each element with the value length
.Pros and Cons of Each Approach
Array.from()
with a callback function:Array(length).fill(length)
:Other Considerations
from
method is part of the ECMAScript standard, so it's supported by most modern browsers. However, some older browsers might not support it.fill()
method is also widely supported, but its behavior can vary depending on the browser and version.Library Used
None in this case, as both approaches use built-in JavaScript methods.
Special JS Features or Syntax
The benchmark uses a syntax feature common to modern JavaScript: template literals (\r\n
). However, it's worth noting that older browsers might not support this feature or might interpret it differently.
Benchmark Preparation Code and Test Cases
The benchmark preparation code is empty, as the script itself contains all the necessary logic. The test cases are defined in the Individual test cases
section, which describes two separate scenarios:
**: This test case uses the
Array.from()` method with a callback function.**: This test case uses the
Array(length).fill(length)` approach.Alternatives
If you wanted to run this benchmark in a different environment, you could consider using:
Keep in mind that the specific implementation details might vary depending on your chosen platform and tools.