class ClassPoint {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(point) {
this.x = this.x + point.x
this.y = this.y + point.y
}
sub(point) {
this.x = this.x - point.x
this.y = this.y - point.y
}
}
function FunctionPoint(x, y){
this.x = x;
this.y = y;
}
FunctionPoint.prototype.add = function(point){
this.x = this.x + point.x
this.y = this.y + point.y
}
FunctionPoint.prototype.sub = function(point){
this.x = this.x - point.x
this.y = this.y - point.y
}
function ObjectPoint(x, y){
return {
x,
y,
add:(point) => {
this.x = this.x + point.x
this.y = this.y + point.y
},
sub:(point) => {
this.x = this.x - point.x
this.y = this.y - point.y
},
}
}
class Base {
constructor(x, y){
this.x = x;
this.y = y;
}
}
class ClassPoint2 extends Base {
add(point){
this.x = this.x + point.x
this.y = this.y + point.y
}
sub(point){
this.x = this.x - point.x
this.y = this.y - point.y
}
}
var p1 = new ClassPoint(10, 10);
var p2 = new ClassPoint(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
var p1 = new FunctionPoint(10, 10);
var p2 = new FunctionPoint(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
var p1 = ObjectPoint(10, 10);
var p2 = ObjectPoint(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
var p1 = new ClassPoint2(10, 10);
var p2 = new ClassPoint2(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ES6 Class | |
Function Prototype | |
Object Literal | |
Class extends |
Test name | Executions per second |
---|---|
ES6 Class | 80367560.0 Ops/sec |
Function Prototype | 86437768.0 Ops/sec |
Object Literal | 9827788.0 Ops/sec |
Class extends | 55557320.0 Ops/sec |
The benchmark defined in the JSON tests various object-oriented programming styles in JavaScript by implementing a simple point class system. Specifically, it compares four different approaches for creating a point-centered object and performing addition and subtraction operations on it:
ClassPoint
)FunctionPoint
)ObjectPoint
)ClassPoint2
)ES6 Class:
class
syntax to create a class ClassPoint
. Instances of this class can add and subtract from other instances.Function Prototype:
FunctionPoint
is defined, and methods are added to its prototype.Object Literal:
Class with Inheritance:
ClassPoint2
extends a Base
class, inheriting its properties and methods, while also defining additional methods.Looking at the execution performance metrics provided:
Other alternatives not explicitly tested in this benchmark include:
Object.create()
, which is an alternative for defining prototype-based inheritance.Float32Array
) may serve better in scenarios requiring a large number of operations on large datasets.In conclusion, the benchmark presents different JavaScript object-oriented styles, outlining their pros and cons based on performance metrics. These considerations are crucial for software engineers to determine the best approach based on their application's specific requirements and performance expectations.