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 | 222831.0 Ops/sec |
bind | 227481.4 Ops/sec |
call | 225925.9 Ops/sec |
apply | 223383.6 Ops/sec |
method call | 213645.9 Ops/sec |
Measuring JavaScript performance is crucial for optimizing code, and MeasureThat.net provides an excellent platform for doing so.
Overview of the Benchmark
The provided benchmark compares the performance of different ways to invoke functions in JavaScript:
test1("World", "Hello");
test2.bind("World", "Hello")();
test3.call("World", "Hello");
test4.apply("World", ["Hello"]);
"World".test5("Hello")
Each test case is a separate benchmark, and the results are displayed for each browser, device platform, operating system, and execution rate.
Options Compared
The five options compared in this benchmark all aim to achieve a similar goal: invoking a function with specific arguments. However, they differ in how they approach this:
test1
with the provided arguments.this
context and argument values to test2
.this
context and argument values as separate arguments to test3
.this
context and argument values as an array to test4
.Pros and Cons
Here's a brief summary of each approach:
this
is not the global object or an object property.this
context and argument values as an array, which can be useful in certain situations.Library/Features Used
In the provided benchmark, no specific JavaScript library is used. However, MeasureThat.net's custom JavaScript execution engine might have some internal optimizations or features that affect the results.
Special JS Features/Syntax
This benchmark does not use any special JavaScript features or syntax beyond what's standard in modern JavaScript engines (ES6+).
Alternatives
If you're interested in exploring alternative methods for invoking functions, here are a few options:
function Foo(name) { return name; };
)test5
method on strings.Each of these alternatives has its own trade-offs and use cases. For the purpose of benchmarking performance-critical code, direct calls or bound/called methods might still be the most suitable choices.