const n = 10;
const n = 10;
const arr = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
arr[i] = i;
}
const n = 10;
const arr = [];
for (let i = 0; i < n; i++) {
arr.push(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
pre | |
non |
Test name | Executions per second |
---|---|
pre | 4532824.0 Ops/sec |
non | 31109536.0 Ops/sec |
I'd be happy to explain the benchmark test.
Overview
The test measures how fast JavaScript can create and populate an array using two different approaches: creating an empty array and then pushing elements, or creating an array with a specified length and filling it with zeros.
Options Compared
Two options are compared:
n
using the new Array(n).fill(0)
method, followed by a loop to populate each element.[]
, then pushes elements into it using a loop.Pros and Cons
new Array(n).fill(0)
method creates a contiguous block of zeros, which can be more efficient.Library Used
None. The test does not use any external libraries.
Special JavaScript Features or Syntax
The test uses the fill()
method to populate the array with zeros, which is a modern JavaScript feature introduced in ECMAScript 5 (ES5). This feature is widely supported across modern browsers and JavaScript engines.
Other Considerations
Other considerations include:
n
) has a significant impact on performance. Larger arrays are more likely to favor the "pre" approach.new Array(n).fill(0)
method differently, affecting performance.Alternatives
Other alternatives to these approaches could include:
Array.prototype.map()
or Array.prototype.slice()
to create and populate an array.