SetTimeout by object method - ES5 binding or closure?

Say I'm doing an animation with an HTML5 canvas. If I'm looking to animate an object's method, which would be preferable, the performance would be reasonable (assuming I don't care about IE8):

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

or

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

My special case is not intense enough to really make a difference visually; I'm just trying to find the best practice.

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

+8
javascript html5-canvas
source share
1 answer

JavaScript performance issues are complex because the different engines out there have very different performance characteristics. What is fast on one engine is slower on another.

Your closure should be very fast; after all, all functions are closures, and your self variable is defined in the context-containing context (so there’s not much to it).

But theoretically, an engine that supports ES5 functions can optimize the operation of bind , making it even faster (there is no need even to search for one chain).

Does it matter? Not. I would use what makes sense to you. Please note that IE8 is not the only browser that does not yet have ES5 features natively (although you can always use one of the es5 gaskets, unlike some ES5 functions, bind can be perfectly emulated with gaskets in ES3 code, although they should use call to do this / apply , which may be slower than shorting on some engines).

+5
source share

All Articles