class Foo1 {
property = 5;
method() {
this.property += 1;
}
}
function Bar1() {
return {
property: 5,
method() {
this.property += 1;
}
};
}
function Bar2() {
let property = 5;
return {
method: () => {
property += 1;
}
};
}
var foo1 = new Foo1();
var foo1Apply = foo1.method;
var foo1Bind = foo1.method.bind(foo1);
var bar1 = Bar1();
var bar1Apply = bar1.method;
var bar1Bind = bar1.method.bind(bar1);
var bar2 = Bar2();
var bar2Variable = bar2.method;
foo1.method();
foo1Apply.apply(foo1);
foo1Bind();
bar1.method();
bar1Apply.apply(bar1);
bar1Bind();
bar2.method();
bar2Variable();
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Class: direct | |
Class: apply | |
Class: bind | |
Object literal: direct | |
Object literal: apply | |
Object literal: bind | |
Object with context: direct | |
Object with context: variable |
Test name | Executions per second |
---|---|
Class: direct | 398258880.0 Ops/sec |
Class: apply | 279955200.0 Ops/sec |
Class: bind | 55733584.0 Ops/sec |
Object literal: direct | 282577888.0 Ops/sec |
Object literal: apply | 289969504.0 Ops/sec |
Object literal: bind | 55094104.0 Ops/sec |
Object with context: direct | 394821344.0 Ops/sec |
Object with context: variable | 277841920.0 Ops/sec |
I'll explain the benchmark and its results in detail.
Benchmark Overview
The benchmark tests four different ways to call a method on an object or class instance:
foo1.method()
or bar1.method()
)bar1.method()
without apply()
or bind()
)bar1Apply.apply(bar1)
)foo1Bind()
)Options Compared
The benchmark compares the execution performance of each method calling approach.
apply()
method to call the method on the object or class instance, passing the context as an argument.bind()
method to create a new function that calls the method on the object or class instance, with the original context.Pros and Cons
Here are some pros and cons of each approach:
Libraries and Features
There are no libraries used in this benchmark. However, it does rely on some JavaScript features, such as:
class
and constructor
syntax for defining classes.() => { ... }
) for defining methods.bind()
method for creating bound functions.Other Alternatives
Some alternative approaches to calling methods on objects or class instances include:
curry()
) to pre-wound the function call.These alternatives may offer performance benefits or improved flexibility in certain scenarios, but they often add complexity and may not be suitable for all use cases.