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 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);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ES6 Class | |
Function Prototype | |
Object Literal |
Test name | Executions per second |
---|---|
ES6 Class | 10770377.0 Ops/sec |
Function Prototype | 9958060.0 Ops/sec |
Object Literal | 299722.6 Ops/sec |
Let's break down what's being tested in the provided JSON benchmark.
Benchmark Definition
The test compares three different techniques for constructing class objects:
class
keyword to define a class, which is the recommended way to create classes in modern JavaScript.{}
) and defining methods directly on the object.Options Compared
The test compares the performance and memory usage of each approach:
add
and sub
methods.Pros and Cons of Each Approach
this
instead of property names)Library
The Point
class (or its variations) uses no external libraries. It's a simple example class for testing the performance of different construction techniques.
Special JS Feature/Syntax
None mentioned in this benchmark definition.
Other Alternatives
If you wanted to test other construction techniques, you could consider:
function Point() { ... }
) instead of classes or function prototypes.var Point = class { ... }
), which are similar to ES6 classes but with a different syntax.Keep in mind that the test results might vary depending on the specific use case and requirements. This benchmark is designed to provide a general comparison of three common approaches to constructing class objects in JavaScript.