let scopeX = 0;
function Constructor(f) {
return Object.setPrototypeOf(f, Constructor.prototype);
};
Constructor.prototype = {
get x() {
return scopeX;
},
y() {
scopeX = scopeX + 1;
}
};
Object.setPrototypeOf(Constructor, Function);
Object.setPrototypeOf(Constructor.prototype, Function.prototype);
var makeConstructor = name => new Constructor(({
[name]() {
return "My name is\n" + name;
}
})[name]);
var aConstructor = makeConstructor("Chika-chika\nSlim Shady");
literalPrototype = {
get x() {
return scopeX;
},
y() {
scopeX = scopeX + 1;
}
};
Object.setPrototypeOf(literalPrototype, Function.prototype);
var makeLiteral = name => Object.setPrototypeOf(({
[name]() {
return "My name is\n" + name;
}
})[name], literalPrototype);
var aLiteral = makeConstructor("Chika-chika\nSlim Shady");
const aConstructor = makeConstructor("Chika-chika\nSlim Shady");
var aLiteral = makeConstructor("Chika-chika\nSlim Shady");
aConstructor();
aLiteral();
aConstructor.y()
aLiteral.y();
const value = aConstructor.x;
const value = aLiteral.x;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
makeConstructor | |
makeLiteral | |
invoke aConstructor | |
invoke aLiteral | |
invoke prototype method aConstructor | |
invoke prototype method aLiteral | |
getter aConstructor | |
getter aLiteral |
Test name | Executions per second |
---|---|
makeConstructor | 835984.8 Ops/sec |
makeLiteral | 873508.4 Ops/sec |
invoke aConstructor | 10111645.0 Ops/sec |
invoke aLiteral | 10260750.0 Ops/sec |
invoke prototype method aConstructor | 9628953.0 Ops/sec |
invoke prototype method aLiteral | 10018681.0 Ops/sec |
getter aConstructor | 10158993.0 Ops/sec |
getter aLiteral | 10195548.0 Ops/sec |
Benchmark Overview
MeasureThat.net provides a JavaScript microbenchmarking platform, where users can create and run their own benchmarks to compare the performance of different approaches. The provided benchmark measures the performance of two ways to create objects in JavaScript: using the Constructor
function and literal object creation.
Constructor vs Literal Object Creation
The benchmark compares the execution speed of two approaches:
Constructor
function to define an object prototype with getters and setters.Options Compared
Both approaches are compared in terms of their performance, specifically:
aConstructor.x
)aConstructor.y()
)Pros and Cons
Libraries and Special Features
This benchmark does not use any external libraries. However, it relies on standard JavaScript features such as classes, getters, and setters.
Other Alternatives
To run this benchmark, you would:
Please note that the results of this benchmark may vary depending on the specific JavaScript engine, browser, and environment used to run it.