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(null), fn2.bind(null), fn3.bind(null), fn4.bind(null)]
}
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 | 3340.2 Ops/sec |
closure | 263489.5 Ops/sec |
Let's break down the provided benchmark and its options.
Overview
The benchmark is designed to compare two approaches: binding functions with null
(bind
) and creating closures over functions (closure
). The test creates an array of four bound functions (fn1
, fn2
, fn3
, and fn4
) in both cases and executes each function 100 times.
Options being compared
There are two main options:
null
(bind
):bind()
method is used to create a new bound function that calls the original function with null
as its context.null
) and does not "remember" any external state or variables from their surrounding scope.closure
):bind()
.Pros and Cons
Binding with null
(bind
):
Pros:
Cons:
bind()
is called, which can incur overhead due to the creation of additional objects and potential garbage collection.Creating closures over functions (closure
):
Pros:
Cons:
Library usage
In this benchmark, there are no notable library dependencies. However, the bind()
method is a built-in JavaScript function that is part of the ECMAScript standard.
Special JS features or syntax
There are no special JavaScript features or syntax explicitly mentioned in the benchmark code.
Other considerations
When using closures, it's essential to be mindful of the following:
() =>
will inherit the context of its surrounding scope.Alternatives
Other approaches for testing binding and closures might include:
ArrowFunctionExpression
instead of FunctionExpression
to create arrow functions.