class Es6Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(point) {
return new Es6Point(this.x + point.x, this.y + point.y);
}
sub(point) {
return new Es6Point(this.x - point.x, this.y - point.y);
}
}
const p1 = new Es6Point(10, 10);
const p2 = new Es6Point(10, -10);
const sum = p1.add(p2);
const dif = p1.sub(p2);
function ProtoPoint(x, y) {
this.x = x;
this.y = y;
}
ProtoPoint.prototype.add = function(point) {
return new ProtoPoint(this.x + point.x, this.y + point.y);
}
ProtoPoint.prototype.sub = function(point) {
return new ProtoPoint(this.x - point.x, this.y - point.y);
}
const p1 = new ProtoPoint(10, 10);
const p2 = new ProtoPoint(10, -10);
const sum = p1.add(p2);
const dif = p1.sub(p2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Es6 | |
Prototype |
Test name | Executions per second |
---|---|
Es6 | 930983.5 Ops/sec |
Prototype | 960012.7 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, compared, and discussed.
What is being tested?
The primary focus of this benchmark is to compare the performance of two approaches to create a class or object in JavaScript:
Point
class with methods add
and sub
.ProtoPoint
function that returns an object with x
and y
properties, and then adds two methods add
and sub
to its prototype.Options being compared
The benchmark compares the performance of:
Pros and Cons
Here are some pros and cons of each approach:
ES6 Classes
Pros:
Cons:
Prototype-Based Classes
Pros:
Object.create()
)Cons:
Other considerations
When deciding between these approaches, consider the specific requirements of your project, such as:
Library and special JS features
Neither test case uses any external libraries. The focus is solely on comparing the performance of ES6 classes and prototype-based classes.
Special JS features (not mentioned)
Since neither test case uses any special JavaScript features, there's no explanation needed.
Alternatives
Some alternatives to consider when creating a class or object in JavaScript include:
function Point(x, y) { ... }
).{ x: 0, y: 0 }
).Keep in mind that each of these alternatives has its own strengths and weaknesses, and the choice ultimately depends on the specific needs of your project.