class PointClass {
constructor(x, y){
this.x = x;
this.y = y;
}
add(point){
return new PointClass(this.x + point.x, this.y + point.y);
}
sub(point){
return new PointClass(this.x - point.x, this.y - point.y);
}
}
function PointProto(x, y){
this.x = x;
this.y = y;
}
PointProto.prototype.add = function(point){
return new PointProto(this.x + point.x, this.y + point.y);
}
PointProto.prototype.sub = function(point){
return new PointProto(this.x - point.x, this.y - point.y);
}
function PointFactory(x, y){
return {
x,
y,
add: (point)=>PointFactory(this.x + point.x, this.y + point.y),
sub: (point)=>PointFactory(this.x - point.x, this.y - point.y)
}
}
window.PointClass = PointClass
window.PointProto = PointProto
window.PointFactory = PointFactory
window.num = 10_000
const points = []
for (let index = 0; index < num; index++) {
points.push(new PointClass(10, 10))
}
const points = []
for (let index = 0; index < num; index++) {
points.push(new PointProto(10, 10))
}
const points = []
for (let index = 0; index < num; index++) {
points.push(PointFactory(10, 10))
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ES6 Class | |
Function Prototype | |
Object Literal |
Test name | Executions per second |
---|---|
ES6 Class | 314.2 Ops/sec |
Function Prototype | 406.2 Ops/sec |
Object Literal | 379.3 Ops/sec |
Let's break down the provided JSON and explain what's being tested, along with the pros and cons of each approach.
Benchmark Definition
The benchmark is testing three different techniques for constructing class objects in JavaScript: ES6 Classes, Function Prototypes, and Object Literals. The goal is to compare their performance and memory usage.
Approaches compared
class
keyword to define a constructor function that creates instances of a class. The class has methods like add
and sub
, which return new instances of the same class.PointProto
, is created with add
and sub
methods that return new instances of the same function.x
and y
. The add
and sub
methods are added as functions to this object.Pros and Cons
Library/Function usage
The benchmark uses the following libraries/functions:
PointClass
, PointProto
, and PointFactory
are custom functions created by the user to demonstrate different approaches to constructing class objects. They are not part of the standard JavaScript library.Special JS features
There are no special JavaScript features (e.g., async/await, generators) used in this benchmark beyond what's necessary for demonstrating the three approaches.
Other alternatives
If you're looking for alternative ways to construct class objects in JavaScript, consider:
class
keyword, you can use a regular function with the same syntax.Keep in mind that these alternatives might not be as readable or maintainable as the approaches demonstrated by the benchmark.