简体   繁体   中英

performance difference between creating a closure and some_func.bind(this)

I'm writing a lot of code in javascript lately and I'm using Prototype.js to help with a lot of the boilerplate, just the bind method is more than worth it since I like using closures instead of objects to do the heavy lifting. It's hard to give up habits picked up from using ruby blocks. So here's my question: Is there any particular performance difference between

var func = some_func.bind(this);
...
func();

and

var that = this;
...
some_func(); // we just rename 'this' everywhere inside some_func to 'that'

These tricks are required because inner functions default to the global context instead of the context of the outer function. In particular which version keeps things more 'flat'. If there is recursion involved then the bind version will come to a crawl because bind will keep folding functions inside functions until unrolling things is impossible, at least I think that's what happens. Does the second version have the same problem.

The performance difference is really extremely negligible unless you are running the operation thousands of times in rapid fire. So I'd usually go with the bind because it makes for cleaner, less bug-prone code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM