var n = 10;
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr.push(i);
}
var n = 10;
var arr = [];
for (var i = 0; i < n; i++) {
arr.push(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array constructor - 10 items | |
Array literal (assign by index) - 10 items |
Test name | Executions per second |
---|---|
Array constructor - 10 items | 5143757.5 Ops/sec |
Array literal (assign by index) - 10 items | 30377936.0 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark compares two approaches to create an array in JavaScript: using the Array
constructor and using literal notation (assigning by index).
Options Compared
There are two options being compared:
Array
class, passing the desired length as an argument.var arr = new Array(n);
arr[i] = i;
).var arr = [];
for (var i = 0; i < n; i++) {
arr.push(i);
}
Pros and Cons
Array
class, which can lead to overhead.Library and Syntax
Neither of these approaches relies on any external libraries or special JavaScript features. The benchmark is focused solely on comparing two basic syntaxes for array creation in JavaScript.
Other Considerations
When considering this benchmark, keep in mind that:
As an alternative, you might consider adding more test cases to cover other aspects of array creation, such as:
Array.from()
or other modern array creation methods.