var n = 100000;
function Person(name, age) {
this.name = name;
this.age = age;
}
var arr = new Array(n);
for (var i = 0; i < n; i++) {
arr[i] = new Person(i + '', i);
}
var arr = [];
for (var i = 0; i < n; i++) {
arr.push(new Person(i + '', i));
}
var arr = [];
for (var i = 0; i < n; i++) {
arr[i] = new Person(i + '', i);
}
var arr = [];
arr.length = n;
for (var i = 0; i < n; i++) {
arr[i] = new Person(i + '', i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array constructor - 100000 items | |
Array literal - 100000 items | |
Array literal (assign by index) - 100000 items | |
Array literal (explicit length) - 100000 items |
Test name | Executions per second |
---|---|
Array constructor - 100000 items | 23.5 Ops/sec |
Array literal - 100000 items | 23.3 Ops/sec |
Array literal (assign by index) - 100000 items | 24.8 Ops/sec |
Array literal (explicit length) - 100000 items | 26.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The benchmark compares the performance of four ways to create an array in JavaScript: using the new Array()
constructor, literal syntax ([]
), assigning elements by index (arr[i] = new Person(i + '', i)
), and explicit length assignment (arr.length = n; arr[i] = new Person(i + '', i)
).
Options Compared
new Array()
constructor.[]
).arr[i] = new Person(i + '', i)
.arr.length = n;
and then assigns elements using arr[i] = new Person(i + '', i)
.Pros and Cons
Library Usage
The benchmark uses an external library called Person
which is not explicitly mentioned in the provided JSON. Assuming it's a custom class, its purpose is likely to represent a person with name and age properties.
Special JavaScript Feature/Syntax
None of the options mentioned in the benchmark require special JavaScript features or syntax that would affect their performance.
Alternatives
Other alternatives for creating arrays in JavaScript include:
Array.from()
: Creates an array from an iterable, such as an array expression.Array.prototype.slice()
: Creates a shallow copy of a portion of an array.Keep in mind that the choice of array creation method depends on the specific use case and performance requirements.