PDA

View Full Version : Scope vs. Closure: Which is faster?



shadun
16 Aug 2007, 4:25 AM
After having programmed about a fourth of my little project I start wondering about the performance issues with JS. More specific, I wonder if there is a performance difference between using a closure or working with correct scopes.

For example, looking at this code snippet:



//Code Snippet using Closure
var me = this; //closured variable

new Button({
text: 'Test',
handler: function(){
me.somefunction(); //using closure
}
});

//Same Snippet using Scope
var me = this;

new Button({
text: 'Test',
handler: function(){
this.somefunction
},
scope: me //using scope
});


Now, which one is faster, and which one uses less resources/memory. And when is the variable that is used as a closure (in this example 'me') being garbage-collected? I would really appreciate a pro answering that question. I (and certainly the other Ext-users) want to make the most out of the Ext-library, and that includes performance. Thanks in advance :)

Animal
16 Aug 2007, 4:28 AM
A closure will be created anyway. You should use



new Button({
text: 'Test',
handler: this.somefunction,
scope: this
});