function fn1() {
return 1 + 1;
}
function fn2() {
return 2 + 2;
}
function fn3() {
return 3 + 3;
}
function fn4() {
return 4 + 4;
}
function createSomething() {
return [fn1.bind(), fn2.bind(), fn3.bind(), fn4.bind()]
}
for (let i = 0; i < 100; i++) {
let [a, b, c, d] = createSomething();
for (let j = 0; j < 100; j++) {
a();
b();
c();
d();
}
}
function createSomething() {
function fn1() {
return 1 + 1;
}
function fn2() {
return 2 + 2;
}
function fn3() {
return 3 + 3;
}
function fn4() {
return 4 + 4;
}
return [fn1, fn2, fn3, fn4]
}
for (let i = 0; i < 100; i++) {
let [a, b, c, d] = createSomething();
for (let j = 0; j < 100; j++) {
a();
b();
c();
d();
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
bind | |
closure |
Test name | Executions per second |
---|---|
bind | 2878.7 Ops/sec |
closure | 213265.6 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark compares two approaches to function binding in JavaScript: bind
and closure.
What is being tested?
In both test cases, four functions (fn1
, fn2
, fn3
, and fn4
) are defined. Each function returns a simple arithmetic expression (e.g., return 1 + 1;
). The benchmark creates an array of four bound versions of these functions using the bind
method.
Options being compared
The two options being compared are:
bind
method to create bound versions of the functions.bind
method, instead returning the original functions directly.Pros and Cons of each approach:
Other considerations
In both test cases, the functions are called 100 times each from multiple iterations of a loop. This creates a high amount of function call overhead, which can affect the benchmark results.
Library used (if any)
None, as this benchmark does not use any external libraries.
Special JavaScript feature or syntax
The bind
method is a built-in JavaScript method that was introduced in ECMAScript 5. It allows you to bind a function to a specific context, making it easier to call the function with specific arguments.
In contrast, the closure approach used in the benchmark does not use any special features or syntax beyond standard JavaScript functions and loops.
Benchmark results
The latest benchmark results show that:
closure
test has a higher executions per second value (3352.257568359375) compared to the bind
test (261804.3125).However, it's essential to note that this result may not generalize to all scenarios and use cases, as the performance difference between these two approaches can vary depending on the specific requirements of your code.