var n = 1000;
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = i;
}
var n = 1000;
var arr = [];
for (var i = 0; i < n; i++) {
arr.push(i);
}
var n = 1000;
var arr = [];
for (var i = 0; i < n; i++) {
arr[i] = i;
}
var n = 1000;
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 - 1000 items | |
Array literal - 1000 items | |
Array literal (assign by index) - 1000 items | |
Array literal (explicit length) - 1000 items |
Test name | Executions per second |
---|---|
Array constructor - 1000 items | 227036.1 Ops/sec |
Array literal - 1000 items | 150661.5 Ops/sec |
Array literal (assign by index) - 1000 items | 158591.0 Ops/sec |
Array literal (explicit length) - 1000 items | 564172.2 Ops/sec |
Benchmark Overview
The provided benchmark compares the performance of four ways to create an array in JavaScript: using the new Array()
constructor, literal syntax with []
, assigning a length to an empty array, and literal syntax with explicit length assignment.
Test Cases
Each test case consists of a single line of code that creates an array with 1000 elements. The code is then executed repeatedly to measure performance.
var arr = new Array(n);
n
variable.var arr = [];
push()
method to add elements.push()
, which can be slower than assigning a length.var arr = [];
[]
syntax.var arr = []; arr.length = n;
length
property.push()
.length
property.Library Used
None of the test cases explicitly use a library. However, some browsers may include libraries or extensions that could affect performance.
Special JS Features/ Syntax
The benchmark does not specifically test any special JavaScript features or syntax, such as async/await, let/const, or arrow functions.
Benchmark Results
The latest benchmark results show the following performance data:
Test Name | Executions Per Second |
---|---|
Array literal (explicit length) - 1000 items | 564172.1875 |
Array constructor - 1000 items | 227036.078125 |
Array literal (assign by index) - 1000 items | 158590.953125 |
Array literal - 1000 items | 150661.484375 |
The results indicate that the Array literal (explicit length)
approach is the fastest, followed closely by the Array constructor
approach.
Alternatives
Other alternatives to create arrays in JavaScript include:
Array.from()
method to create an array from an iterable source, such as an array of numbers or strings.Keep in mind that the choice of array creation approach depends on specific use cases and performance requirements.