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);
const pointParent = {
add(point) {
return pointNew(this.x + point.x, this.y + point.y);
}
};
const pointParentParent = {
sub(point) {
return pointNew(this.x + point.x, this.y + point.y);
}
};
Object.setPrototypeOf(pointParent, pointParentParent);
function pointNew (x, y) {
let p = {
x:x,
y:y
}
Object.setPrototypeOf(p, pointParent);
return p
}
let a1 = pointNew(10, 10);
let a2 = pointNew(10, -10);
let sum = a1.add(a2);
let dif = a1.sub(a2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Function Prototype | |
Object Literal |
Test name | Executions per second |
---|---|
Function Prototype | 438241.3 Ops/sec |
Object Literal | 278029.9 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is comparing two approaches to inheritance in JavaScript:
Object.setPrototypeOf()
method to set the prototype of an object, effectively creating a new inheritance hierarchy.Test Cases
There are two test cases:
Point
function with a prototype that inherits from another Point
function using Object.setPrototypeOf()
. It then tests the add()
and sub()
methods on an instance of this inherited function.pointParent
and pointParentParent
, where pointParent
has an add()
method that returns a new Point
object with updated x and y coordinates. The pointParentParent
object has a sub()
method that also returns a new Point
object. It then tests the add()
and sub()
methods on instances of these objects.Options Compared
The benchmark is comparing the performance of two approaches:
Object.setPrototypeOf()
to create an inheritance hierarchy.Pros and Cons
Prototype-based Inheritance:
Pros:
Cons:
Object.setPrototypeOf()
.Object Literal-based Inheritance:
Pros:
Object.setPrototypeOf()
.Cons:
Libraries Used
In this benchmark, no specific libraries are mentioned. However, it's worth noting that some JavaScript frameworks or libraries may use these approaches differently or provide additional features that affect performance.
Special JS Features or Syntax
No special JavaScript features or syntax are mentioned in the benchmark definition or test cases.
Alternatives
Other alternatives for inheritance in JavaScript include:
Object.assign()
to merge properties from multiple objects, effectively creating a mixin that can be applied to other objects.These alternatives have their own trade-offs in terms of flexibility, performance, and code readability.