Performance React: Anonymous Function Binding
I would like to know if there is a performance difference between using bind
and anonymous function in React components.
Specifically, is one of the following more effective than the other?
const MyComponent = ({ myHandler }) => {
...
return (
<a onClick={myHandler.bind(this, foo, bar)} ...>
hello world
</a>
);
}
const MyComponent = ({ myHandler }) => {
...
return (
<a
onClick={() => {
myHandler(this, foo, bar)
}
...
>
hello world
</a>
);
}
This question is different from the possible duplicate because the answer to the possible duplicate question focuses on the memory area.
source to share
First, the way you ask your question is a little flawed:
Your first example <a onClick={myHandler.bind(this, foo, bar)} ...>
creates a new function for each render, tied to the component context and always has foo
and bar
as the first two arguments.
The second example <a onClick={() => myHandler(this, foo, bar)} ...>
instead causes myHandler
the three arguments this
, foo
and bar
where it is a component context.
On a theoretical level, you are discussing two concepts: this
does bind to a function more costly than creating a new anonymous bound function and calling the function there? I would say that both approaches are very similar in terms of performance: you create a new function ( func.bind docs ) in both cases.
Any differences in performance will be so small that you probably never develop such a critical time for the performance of the software, where the choice between () => {}
, and bind
would be a problem.
If you want to improve performance here, select class
and bind a click handler to context in constructor
. This way you don't have to create a new function every time you render.
Hope it helps
source to share