Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout on object method - ES5 bind, or closure?

Let's say I'm doing some animations with the HTML5 Canvas. If I'm looking to animate an object's method, which would be preferable, performance wise (assuming I don't care about IE8):

setTimeout(this.render.bind(this), 15);

or

var self = this;
setTimeout(function () { self.render() }, 15);

My particular case isn't intense enough to really make a difference visually; I'm just trying to find out the best practice.

I would think creating a new function with bind would have less overhead than creating a closure, but I wanted to ask the experts.

like image 867
Adam Rackis Avatar asked Jan 19 '12 15:01

Adam Rackis


1 Answers

JavaScript performance questions are tricky, because the various engines out there have very different performance characteristics. What's fast on one engine is slow on another.

Your closure should be very fast indeed; after all, all functions are closures and your self variable is defined in the immediately-containing context (so there isn't a lot of looking through the scope chain for it).

But in theory, an engine that supports ES5 features natively could optimize how bind works, making it even faster (no need for even just the one scope chain lookup).

Does it matter? No. I'd use what makes sense to you. Note that IE8 isn't the only browser out there that doesn't yet have ES5 features natively (although you can always use one of the es5 shims; unlike some ES5 features, bind can be perfectly emulated by shims in ES3 code — although to do it they have to use call/apply, which may be slower than a closure on some engines).

like image 112
T.J. Crowder Avatar answered Oct 20 '22 16:10

T.J. Crowder