简体   繁体   English

创建闭包和some_func.bind(this)之间的性能差异

[英]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. 我最近用javascript写了很多代码,并且我使用Prototype.js来帮助完成很多样板工作,因为我喜欢使用闭包而不是对象来完成繁重的工作,所以bind方法非常值得。 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. 所以我通常会选择绑定,因为它可以使代码更简洁,更不易出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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