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);
const Point = class {
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);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ES6 Class | |
Function Prototype | |
Object Literal | |
anonymous class |
Test name | Executions per second |
---|---|
ES6 Class | 337743.0 Ops/sec |
Function Prototype | 313252.7 Ops/sec |
Object Literal | 1400763.2 Ops/sec |
anonymous class | 342265.8 Ops/sec |
Let's break down what is being tested in the provided JSON benchmark.
Benchmark Overview
The test measures the speed and memory usage of constructing class objects using three different approaches:
class
keyword.Approach Comparison
Each approach has its pros and cons:
class
keyword.prototype
and this
.class
keyword.Library Usage
None of the tests explicitly use external libraries. However, some might use built-in library functions or methods (e.g., String.prototype.replace()
).
Special JS Features/Syntax
This benchmark does not explicitly test any special JavaScript features or syntax. It only focuses on the differences in constructing class objects using the three approaches.
Alternatives
Other alternatives to these approaches include:
this
set as a property (e.g., function Point(x, y) { this.x = x; this.y = y; }
).These alternatives are not directly related to the specific construction of class objects but can be used in other contexts for building classes and objects in JavaScript.