loading...

re: This and Bind In Javascript VIEW POST

FULL DISCUSSION
 

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));

or

window.addEventListener('click', ()=> this.doSomething());

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.

 

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.

 

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.

Code of Conduct Report abuse