var times = 5000;
var a = new Array();
for (var i = 0; i <= times; i++) {
a.push(1337)
}
var b = new Array(times);
for (var i = 0; i <= times; i++) {
b.push(1337)
}
var c = [];
for (var i = 0; i <= times; i++) {
c.push(1337)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array Constructor | |
Array Size Constructor | |
Array Literal |
Test name | Executions per second |
---|---|
Array Constructor | 1233.8 Ops/sec |
Array Size Constructor | 1350.1 Ops/sec |
Array Literal | 1797.0 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of three different ways to initialize an array in JavaScript: using the new Array()
constructor, new Array(times)
constructor, and an array literal ([]
).
Test Cases
There are three test cases:
new Array()
constructor to create an array and then pushes 1337 into it times
number of times.new Array(times)
constructor to create an array with a specific size (times
) and then pushes 1337 into it times
number of times.[]
) to create an empty array and then pushes 1337 into it times
number of times.Library Usage
None of the test cases use any external libraries.
Special JavaScript Features/Syntax
None of the test cases utilize any special JavaScript features or syntax. They only rely on standard JavaScript features and syntax.
Benchmark Comparison
The benchmark compares the performance of these three methods:
new Array()
and then pushes elements into it.new Array(times)
and then pushes elements into it.new Array()
since it creates an array with a specific size, reducing the overhead.[]
and then pushes elements into it.Benchmark Results
The latest benchmark results show that:
These results suggest that using an array literal is generally the most efficient way to initialize an array in JavaScript.
Other Alternatives
If you need to create a large array or an array with a specific size, you might consider using other alternatives:
new Array(times)
with a specific length and then filling some elements with values.Keep in mind that these alternatives might not be as straightforward to use as the original methods, but they can provide additional options depending on your specific use case.