function test(msg) {
//console.log(this, msg);
}
function test1(self, msg) {
//console.log(self, msg);
}
function test2(msg) {
//console.log(this, msg);
}
function test3(msg) {
//console.log(this, msg);
}
function test4(msg) {
//console.log(this, msg);
}
String.prototype.test5 = function(msg) {
//console.log(this, msg)
}
test1("World", "Hello");
test2.bind("World", "Hello")();
test3.call("World", "Hello");
test4.apply("World", ["Hello"]);
"World".test5("Hello")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
direct call | |
bind | |
call | |
apply | |
method call |
Test name | Executions per second |
---|---|
direct call | 12885965.0 Ops/sec |
bind | 10496329.0 Ops/sec |
call | 10522191.0 Ops/sec |
apply | 9681875.0 Ops/sec |
method call | 909749184.0 Ops/sec |
Let's break down the provided benchmark and its various test cases.
Benchmark Overview
The benchmark measures the performance of different ways to call a function in JavaScript, specifically when it comes to accessing the this
context. The tests compare the execution time of direct function calls (test1
, test2
, test3
, test4
) versus using bind
, call
, and apply
methods.
Test Cases
Each test case represents a different way to call a function:
test1("World", "Hello");
test2.bind("World", "Hello")();
bind
method creates a new function that has its this
context set to the specified value.this
context.test3.call("World", "Hello");
call
method calls a function with its specified this
context and arguments.test4.apply("World", ["Hello"]);
apply
method calls a function with its specified this
context and an array of arguments."World".test5("Hello")
bind
/call
/apply
.JavaScript Library
None are explicitly mentioned, but it's worth noting that some browsers may have optimizations for certain methods. For example, modern JavaScript engines often optimize call
and apply
by inlining or hoisting the function calls.
Special JS Feature
The bind
method is using a modern JavaScript feature (ECMAScript 2015+) to create a new function with its this
context set. This is done using the bind
method's syntax, which creates a new function that takes the specified arguments and has its this
context set accordingly.
Alternatives
Other approaches could be used to call functions in JavaScript:
() => { ... }
) can simplify the code and avoid the need for explicit this
binding.function Constructor(...args) { ... }
can provide a way to create objects with a specific this
context.Keep in mind that these alternatives might not be as efficient or concise as the original test cases.