class Point {
constructor(x, y){
this.x = x;
this.y = y;
}
add(point){
return new Point(this.x + point.x, this.y + point.y);
}
sub(point){
return new Point(this.x - point.x, this.y - point.y);
}
}
var p1 = new Point(10, 10);
var p2 = new Point(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
function Point(x, y){
this.x = x;
this.y = y;
}
Point.prototype.add = function(point){
return new Point(this.x + point.x, this.y + point.y);
}
Point.prototype.sub = function(point){
return new Point(this.x - point.x, this.y - point.y);
}
var p1 = new Point(10, 10);
var p2 = new Point(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
function Point(x, y){
return {
x,
y,
add: (point)=>Point(this.x + point.x, this.y + point.y),
sub: (point)=>Point(this.x - point.x, this.y - point.y)
}
}
var p1 = Point(10, 10);
var p2 = Point(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 |
Test name | Executions per second |
---|---|
ES6 Class | 1236791.9 Ops/sec |
Function Prototype | 998467.5 Ops/sec |
Object Literal | 2826506.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three different approaches for constructing class objects in JavaScript:
Options Compared
Point
objects with different coordinates, performing addition and subtraction operations using these objects.Pros and Cons of Each Approach
this
binding.Library Used
There is no library explicitly mentioned in the benchmark. However, the Point
class definition uses a common pattern for prototypal inheritance, where methods are defined on the prototype object rather than an instance.
Special JS Feature/ Syntax
The benchmark uses ES6 features such as classes (ES6 Class), function prototypes (Function Prototype), and template literals (Object Literal). These features provide concise syntax for creating objects, but may not be compatible with older browsers or environments that don't support them.
Other Alternatives
If you need to compare other approaches for constructing class objects in JavaScript, consider the following alternatives:
Keep in mind that each approach has its trade-offs, and the best choice depends on your specific use case, performance requirements, and personal preference.