const a = [];
let i = 0;
while (i < 10000) {
const d = {};
a.push({ b: i });
i++;
}
const a = [];
const c = function(i) {
this.b = i;
}
let i = 0;
while (i < 10000) {
a.push(new c(i));
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object literal | |
Constructor |
Test name | Executions per second |
---|---|
Object literal | 2606.1 Ops/sec |
Constructor | 2587.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition and Purpose
The provided JSON represents a benchmark definition, which describes two test cases: "Object literal" and "Constructor". The benchmark measures the performance difference between creating objects using an object literal (i.e., const d = {}
) versus using a constructor function (i.e., new c(i)
).
Options Compared
In this benchmark, we have two main options being compared:
const d = {}
) and then pushes a new object with properties into the array (a.push({ b: i })
).c(i)
that takes an argument i
, sets the b
property on the instance, and returns the instance. The instance is then pushed into the array using a.push(new c(i))
.Pros and Cons of Each Approach
Library Used
In both benchmark definitions, there is no explicit library being used. However, JavaScript's built-in Array.prototype.push()
method is used to add elements to the array a
. There are no external libraries or dependencies required for these tests.
Special JS Feature/Syntax
There are a few special features and syntax in these benchmarks:
function(i) { ... }
and const c = function(i) { ... }
) to define the constructor function.Other Alternatives
If you wanted to test alternative approaches, here are some possibilities:
class D { b = i; }
).However, these alternatives are not directly relevant to the "Constructor vs object literal" benchmark on MeasureThat.net.