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 | 25.1 Ops/sec |
Array literal - 100000 items | 23.0 Ops/sec |
Array literal (assign by index) - 100000 items | 24.8 Ops/sec |
Array literal (explicit length) - 100000 items | 26.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, the different approaches compared, their pros and cons, and other considerations.
Benchmark Overview
The benchmark measures the performance of creating an array with a custom Person
object using four different methods:
Array
constructor with explicit length assignment (Array constructor - 100000 items
)Array
constructor without explicit length assignment (Array literal - 100000 items
)[]
syntax for array creation and assigning elements by index (Array literal (assign by index) - 100000 items
)[]
syntax for array creation with explicit length assignment (Array literal (explicit length) - 100000 items
)Methods Comparison
new Person()
constructor.new Person()
constructor.new Person()
constructor, similar to the previous method.new Person()
constructor.new Person()
constructor.new Person()
constructor.Other Considerations
Person
class, which is a custom class that represents an individual. Its purpose is not explicitly stated in the benchmark, but it seems to be used for testing purposes only.Alternatives
If you were to create similar benchmarks for other array creation methods, you could consider the following alternatives:
Array.from()
methodMap
objects with the set()
methodSet
objects with the add()
methodBuffer
or TypedArray
constructorsKeep in mind that these alternatives might have different performance characteristics and may not be suitable for all use cases.