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 Point1 = Point;
function Point2(x, y) {
this.x = x;
this.y = y;
}
Point2.prototype.add = function(point) {
return new Point2(this.x + point.x, this.y + point.y);
}
Point2.prototype.sub = function(point) {
return new Point2(this.x - point.x, this.y - point.y);
}
function Point3(x, y) {
return {
x,
y,
add: (point) => Point3(this.x + point.x, this.y + point.y),
sub: (point) => Point3(this.x - point.x, this.y - point.y)
}
}
var add = (a, b) => (a.x + b.x, a.y + b.y)
var sub = (a, b) => (a.x - b.x, a.y - b.y)
var p1 = new Point1(10, 10);
var p2 = new Point1(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
var p1 = new Point2(10, 10);
var p2 = new Point2(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
var p1 = Point3(10, 10);
var p2 = Point3(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
var p1 = {x:10, y:10};
var p2 = {x:10, y:-10};
var sum = add(p1, p2);
var dif = sub(p1, p2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ES6 Class | |
Function Prototype | |
Object Literal | |
Functional |
Test name | Executions per second |
---|---|
ES6 Class | 171140640.0 Ops/sec |
Function Prototype | 217401216.0 Ops/sec |
Object Literal | 2575268.2 Ops/sec |
Functional | 238724688.0 Ops/sec |
The benchmark you're analyzing compares four different JavaScript coding styles for implementing a point-like structure that can perform two operations: addition and subtraction of points. Here's a breakdown of the various approaches tested, their pros and cons, and other considerations.
ES6 Class
Point
class is defined with a constructor and methods for adding and subtracting points.var p1 = new Point1(10, 10);
var p2 = new Point1(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
Function Prototype
Point2
creates instances, and methods are added to its prototype.var p1 = new Point2(10, 10);
var p2 = new Point2(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
this
could be incorrectly referenced.Object Literal
var p1 = Point3(10, 10);
var p2 = Point3(10, -10);
var sum = p1.add(p2);
var dif = p1.sub(p2);
new
.Functional
var p1 = {x:10, y:10};
var p2 = {x:10, y:-10};
var sum = add(p1, p2);
var dif = sub(p1, p2);
From the benchmark results, we observe the following execution rates:
The functional approach performed the best, likely due to its minimal overhead and straightforward execution. The ES6 Class performed better than the Object Literal approach, suggesting that despite being a newer construct, it still provides reasonably good performance due to its optimizations in modern JavaScript engines.
In summary, the benchmark provides valuable insights into different JavaScript paradigms regarding performance and usability, informing developers of the trade-offs they might consider when implementing similar solutions.