DEV Community

Discussion on: This and Bind In Javascript

Collapse
 
agronick profile image
Kyle Agronick

I run into this all the time when I wan to set up a callback. I could either do

window.addEventListener('click', this.doSomething.bind(this));
Enter fullscreen mode Exit fullscreen mode

or

window.addEventListener('click', ()=> this.doSomething());
Enter fullscreen mode Exit fullscreen mode

I wanted to see which one was faster. It turns out bind is about 50% faster when you're calling it thousands of times.

I wanted to see if it was different if I was only calling the callback once. It turns out its the opposite. Bind is about 65% slower.

So it seems like you should use arrow functions for callbacks unless you are going to call it multiple times.

Collapse
 
bbarbour profile image
Brian Barbour

I imagine the speed is difference is hardly even noticeable to the human eye. I tried it and it felt almost the exact same speed.

Collapse
 
agronick profile image
Kyle Agronick

You'll never be able to measure these types of micro-optimizations just by looking at them. But if you were to put this on a mousemove handler it would run hundreds of times a second. That is when using bind would matter.