var n = 10_000;
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = i;
}
var n = 10_000;
var arr = [];
for (var i = 0; i < n; i++) {
arr.push(i);
}
var n = 10_000;
var arr = [];
for (var i = 0; i < n; i++) {
arr[i] = i;
}
var n = 10_000;
var arr = [];
arr.length = n;
for (var i = 0; i < n; i++) {
arr[i] = i;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array constructor - 10_000 items | |
Array literal - 10_000 items | |
Array literal (assign by index) - 10_000 items | |
Array literal (explicit length) - 10 items |
Test name | Executions per second |
---|---|
Array constructor - 10_000 items | 67335.6 Ops/sec |
Array literal - 10_000 items | 36783.3 Ops/sec |
Array literal (assign by index) - 10_000 items | 31192.0 Ops/sec |
Array literal (explicit length) - 10 items | 71399.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of four different ways to create an array in JavaScript:
new Array(n)
[ ]
[i]
inside a looparr.length = n;
Options Comparison
The benchmark tests these four options because:
[]
without setting its length can lead to slower performance in older browsers or with large arrays.arr[i] = i;
) is another common way to populate an array. This approach may be faster than using new Array(n)
but might not be as efficient as literal creation for very large arrays.arr.length = n;
) can be a good compromise between performance and memory usage.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
new Array(n)
, suitable for very large arrays. Cons - may be slower than literal creation for small arrays.Library Usage
None of the benchmark options explicitly uses a JavaScript library. However, modern browsers like Chrome often include libraries or utilities that can influence the results, such as:
Special JS Features/Syntax
The benchmark does not mention any special JavaScript features or syntax, but it's worth noting that older browsers or specific implementations might have different behavior for certain features like let
/const
, arrow functions, or class
declarations.
Alternatives
If you're interested in exploring alternative approaches, consider the following:
Array.prototype.fill()
or Array.prototype.splice()
Uint8Array
) for better performanceKeep in mind that these alternatives might not be directly comparable to the original benchmark options, as they may introduce additional overhead or dependencies.