var n = 10;
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = i;
}
var n = 10;
var arr = [];
for (var i = 0; i < n; i++) {
arr.push(i);
}
var n = 10;
var arr = [];
for (var i = 0; i < n; i++) {
arr[i] = i;
}
var n = 10;
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 items | |
Array literal - 10 items | |
Array literal (assign by index) - 10 items | |
Array literal (explicit length) - 10 items |
Test name | Executions per second |
---|---|
Array constructor - 10 items | 8112736.0 Ops/sec |
Array literal - 10 items | 31976448.0 Ops/sec |
Array literal (assign by index) - 10 items | 26319300.0 Ops/sec |
Array literal (explicit length) - 10 items | 10709304.0 Ops/sec |
Let's break down the provided benchmark and its options.
Benchmark Overview
The test case measures the performance of different approaches to create an array in JavaScript:
Array
constructor with explicit length (new Array(n)
).[]
and then setting length = n
).[]
and using push
to add elements).Benchmark Definitions
There are four test cases:
new Array(n)
.[]
and then setting length = n
.length
, it uses push
to add elements.[]
and then setting length = n
.Options Compared
The benchmark compares the performance of three approaches:
new Array(n)
or []
followed by length = n
.[]
and adding elements using push
, like in test case 3.[...]
) instead of new Array(n)
.Pros and Cons
Here are some pros and cons for each approach:
push
.Library and Special JS Features
There are no notable libraries or special JS features mentioned in the benchmark definitions.
Other Alternatives
If you're interested in exploring alternative approaches, consider the following:
Array.from()
: A more modern approach to creating arrays from scratch.createArray()
function: Can provide additional flexibility and features.Map
or Set
.Keep in mind that the performance differences between these approaches may vary depending on the specific use case and JavaScript engine being used.
In summary, this benchmark provides a useful comparison of three common approaches to creating arrays in JavaScript, highlighting their pros and cons. The choice of approach ultimately depends on your specific requirements and preferences.