class Point {
constructor(x, y){
this.x = x;
this.y = y;
}
}
function add(p1, p2) {
return new Point(p1.x + p2.x, p1.y + p2.y);
}
function sub(p1, p2) {
return new Point(p1.x - p2.x, p1.y - p2.y);
}
var p1 = new Point(10, 10);
var p2 = new Point(10, -10);
var sum = add(p1, p2);
var dif = sub(p1, p2);
function Point(x, y){
this.x = x;
this.y = y;
}
function add(p1, p2) {
return new Point(p1.x + p2.x, p1.y + p2.y);
}
function sub(p1, p2) {
return new Point(p1.x - p2.x, p1.y - p2.y);
}
var p1 = new Point(10, 10);
var p2 = new Point(10, -10);
var sum = add(p1, p2);
var dif = sub(p1, p2);
function add(p1, p2) {
return Point(p1.x + p2.x, p1.y + p2.y);
}
function sub(p1, p2) {
return Point(p1.x - p2.x, p1.y - p2.y);
}
function Point(x, y){
return {
x,
y,
}
}
var p1 = Point(10, 10);
var p2 = Point(10, -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 |
Test name | Executions per second |
---|---|
ES6 Class | 724398.0 Ops/sec |
Function Prototype | 709090.9 Ops/sec |
Object Literal | 67524656.0 Ops/sec |
The benchmark under consideration aims to evaluate the performance of three different JavaScript techniques for constructing class-like objects: ES6 classes, function prototypes, and object literals. The primary focus is on measuring the speed (in terms of executions per second) and potentially memory usage, although the provided results do not explicitly include memory consumption metrics.
ES6 Class:
Point
. It utilizes a constructor method to initialize x
and y
properties.Function Prototype:
Point
is defined that sets properties directly on this
. It relies on JavaScript's prototype system for method inheritance.Object Literal:
x
and y
directly without the use of this
.Other potential alternatives worth mentioning include:
Singleton Pattern: Instantiating a single instance of an object when needed, useful for configurations or shared resources.
Factory Functions: Functions that return objects with specific characteristics or behaviors, allowing for more controlled instantiation and additional logic during creation.
Proxy Design Pattern: Using proxies to control access to another object, adding additional behavior during read or write operations.
Each of these alternatives comes with its own set of trade-offs concerning performance, readability, maintainability, and complexity. Ultimately, the best choice will depend on the specific requirements and constraints of the project.