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 add = (a, b) => ({ x: a.x + b.x, y: a.y + b.y });
const sub = (a, b) => ({ x: a.x - b.x, y: a.y - b.y });
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 | |
Object Literal & Function |
Test name | Executions per second |
---|---|
ES6 Class | 842472.6 Ops/sec |
Function Prototype | 741919.7 Ops/sec |
Object Literal | 2362710.2 Ops/sec |
Object Literal & Function | 226168048.0 Ops/sec |
Let's dive into the benchmark.
What is tested?
The benchmark tests four different approaches to constructing class objects in JavaScript:
class
keyword to define a class, which includes methods and properties.this
context).Options comparison
The benchmark compares these four approaches in terms of:
ExecutionsPerSecond
.Pros and Cons
this
context.Special JS feature/syntax
None mentioned explicitly, but it's worth noting that ES6 classes have some features like static members (static
keyword) and class inheritance (extends), which might not be relevant in this benchmark.