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) { return Point(this.x + point.x, this.y + point.y)},
sub (point) { return 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 | 282152.5 Ops/sec |
Function Prototype | 228246.7 Ops/sec |
Object Literal | 20172288.0 Ops/sec |
Let's dive into the explanation of the provided benchmark.
The test case is designed to measure the performance and memory usage of three different approaches for constructing class objects in JavaScript:
class
keyword to define a new class, which creates an instance of a constructor function.Point
function that returns an object with methods add
and sub
. The prototype chain is used to add these methods to the Point
function.Comparison Options:
Library/Functionality:
Point
class/function is used throughout all three test cases. It has methods add
and sub
, which return a new instance of Point
.Special JS Features/Syntax:
this
binding and static methods (e.g., static get()
), which might affect performance.Other Alternatives:
new
keyword.Keep in mind that the choice of approach depends on the specific use case, performance requirements, and coding style preferences.