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);
}
}
const points = [];
for(var i = 0; i < 1000; ++i) {
points.push(new Point(i,i));
}
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)
}
}
const points = [];
for(var i = 0; i < 1000; ++i) {
points.push(Point(i,i));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classes | |
literals |
Test name | Executions per second |
---|---|
classes | 4768.9 Ops/sec |
literals | 4336.5 Ops/sec |
Let's dive into the provided benchmark JSON.
Benchmark Definition The benchmark is designed to compare two approaches: using classes and using literals (objects) with methods.
Options Compared
Point
object, which encapsulates its properties (x
, y
) and methods (add
, sub
).x
, y
) and method references (add
, sub
).Pros and Cons of Each Approach
Using Classes
Pros:
Cons:
Using Literals (Objects)
Pros:
Cons:
add
, sub
) requires more code than defining them directly in the class (in this case).Library Usage In both test cases, no libraries are used. The focus is on comparing the two approaches.
Special JS Features or Syntax None of the provided test cases use any special JavaScript features or syntax.
Benchmark Preparation Code
The preparation code is minimal and simply initializes an array points
with 1000 elements, each containing a Point
object (in one of the two tested approaches).
Latest Benchmark Result The benchmark result shows that Chrome Mobile 117 browser executes the class-based approach approximately 10% faster than the literal-based approach.
Now, let's consider other alternatives:
Keep in mind that these alternatives might not directly compare to the class-based and literal approaches tested here, but they could provide interesting variations on the theme.