Alex
Alex

Reputation: 892

Memory overhead of anonymous functions vs named functions when used as Jquery callbacks

I'm learning about JS/JQuery and anonymous functions and closures. I've seen examples like this:

$('.button').click(function(){
    /* Animations */
    /* Other Stuff */
});

If there is more than one button, isn't that inefficient? Isn't that just storing similar copies of an anonymous function's prototype in memory? ( correct my terminology) Isn't it better to do this:

function handleClick(){
    /* Animations */
    /* Other Stuff */
}

('.button').click(handleClick);

Or even this, if a reference to the button is needed:

function handleClick($obj){
    /* Animations */
    /* Other Stuff */
}
//multiple anon functions again, but they all reference ONE handleClick function
('.button').click((function($obj){         
     return function(){handleClick($obj)};
})($(this));

Upvotes: 6

Views: 1368

Answers (2)

Kemal Dağ
Kemal Dağ

Reputation: 2763

When you use named functions, it only lives on a global closure, but if you define functions on runtime, they are created within (parent function's closure) a new closure, resulting in parent variables being preserved after, even if you do not need that function anymore.

In short terms, try anonymous functions only if you need to access variables located in parent function. Anonymous functions are nearly always more expensive then named functions. But named functions defined in global closure, pollutes global namespace, decide for yourself.

Upvotes: 3

NDM
NDM

Reputation: 6830

By design, the observer pattern only keeps one instance of the observer. The event handler then calls this observer multiple times, with other instances of an event object, which holds the event parameters: which element fired the event, what is the context,... etc

So the handler is not duplicated, but referenced in each subject's 'listeners store'.

Note:
Kemal Dag also notes that anonymous functions by definition offer less performance then named function, I don't know if it is true, but if it is, the difference is negligible. Especially for a language as JavaScript, that uses anon functions so extensively, it can not afford a performance impact on it.

Upvotes: 2

Related Questions