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;
}
const pointParent = {
add(point) {
return new Point(this.x + point.x, this.y + point.y);
}
};
const pointParentParent = {
sub(point) {
return new Point(this.x + point.x, this.y + point.y);
}
};
Object.setPrototypeOf(pointParent, pointParentParent);
Point.prototype = pointParent;
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 with longer chain | |
Object Literal |
Test name | Executions per second |
---|---|
ES6 Class | 755218.4 Ops/sec |
Function Prototype with longer chain | 526179.1 Ops/sec |
Object Literal | 1490133.5 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Definition
The benchmark compares three different approaches to create and use an object for mathematical operations:
class
keyword to define a class-based object.Point
function.Options being compared
The benchmark compares these three approaches in terms of performance, specifically:
Pros and Cons of each approach:
Library and its purpose
In this benchmark, the Point
function is used as a library or utility function. Its purpose is to encapsulate mathematical operations (addition and subtraction) on two points in 2D space.
Special JS feature or syntax
The benchmark uses ES6 class syntax (class Point { ... }
) which was introduced in ECMAScript 2015 (ES6). This syntax allows for a more concise way of defining classes, but may not be compatible with older browsers or environments that don't support it.
Other alternatives
If you wanted to rewrite this benchmark using different approaches, some alternatives could be:
Object.create()
and Object.setPrototypeOf()
for prototypal inheritance.However, these alternatives might not offer significant performance benefits over the existing approaches, and would likely require additional setup and maintenance effort.