var n = 10;
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 | 346591.0 Ops/sec |
Array literal - 100000 items | 369011.3 Ops/sec |
Array literal (assign by index) - 100000 items | 393708.1 Ops/sec |
Array literal (explicit length) - 100000 items | 366800.1 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Definition
The test creates an array with 100,000 elements and assigns a Person
object to each element using different methods: constructor and literals (using []
, push()
, and assigning a length).
Options Compared
new Array()
constructor to create the array.[]
and then pushing Person
objects into it using a loop.Person
objects to each element using another loop.[]
and then pushing Person
objects into it without specifying the length.Pros and Cons
length
assignment step.Library Used
None explicitly mentioned, but it's assumed that the Person
class is defined elsewhere in the codebase. The Person
class likely contains properties for name and age, as indicated by its constructor.
Special JS Feature/Syntax
The benchmark uses the push()
method to add elements to the array, which is a built-in JavaScript feature. There are no special JavaScript features or syntax used beyond this.
Other Considerations
new
operator for constructor-based approach might incur additional overhead compared to direct literal creation.Alternatives
If you're interested in exploring alternative approaches or optimizing the existing code, consider:
Uint8Array
, Int8Array
) instead of JavaScript arrays for better performance.Keep in mind that the benchmark's results may not accurately reflect real-world scenarios, as they are influenced by various factors like system architecture, browser versions, and hardware configurations.