var n = 10000;
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 | 2994.9 Ops/sec |
Array literal - 100000 items | 2796.7 Ops/sec |
Array literal (assign by index) - 100000 items | 2794.0 Ops/sec |
Array literal (explicit length) - 100000 items | 2857.3 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark compares the performance of different ways to create an array in JavaScript.
What's being tested?
The test creates an array with 100,000 elements using four different methods:
var arr = new Array(n);
followed by a loop that populates each element.var arr = [];
followed by a loop that assigns elements to the array using indexing (arr[i] = new Person(i + '', i);
).var arr = [];
followed by setting the length of the array to n
and then populating each element.Options compared
The test compares the performance of these four methods:
Pros and Cons
Here's a brief summary of each approach:
Library and Special JS Features
The Person
function is not a built-in JavaScript library, but rather a custom class defined in the script preparation code. It's likely used only for this benchmark to measure the performance of array creation.
Other Considerations
Array.from()
or Array.create()
, are not tested in this benchmark.Alternatives
Other alternatives for creating arrays in JavaScript include:
Array.from()
with an array of objectsArray.create()
with an objectrepeat()
function