views:

66

answers:

3

Is there any performance / memory hit differential among the three following styles?

Exhibit A:

var func = function() {
    // do some magic
}

$("#div").somePlugin({someEvent: func});

Exhibit B:

$("#div").somePlugin({someEvent: function() {
    // do some magic
});

Exhibit C:

function func() {
    // do some magic
}

$("#div").somePlugin({someEvent: func});
A: 

There's no performance hit to speak of, it's more of a re-use/style thing, I'd say. In both A and C, the func becomes reusable, which can be helpful in certain situations. With B, you encapsulate functionality which is often desirable.

I prefer C as it's cleaner to read and enabled reuse without refactoring.

Langdon
A: 

The performance of all three should be near identical. There may be a difference in memory usage depending on where you declared the function, and whether it uses variables from its containing function -- since you'd be creating a closure, which would require references to the variables used -- but not enough to make a difference unless you created the function thousands of times.

cHao
+3  A: 

There might be a little, slightly (really slightly) better performance for the function expression:

var func = function(){
};

That is a such called function expression. The otherside, the function statement is your third example:

function func(){
}

Function statements are converted internally into function expressions by ECMA-/Javascript, so thats the reason why it might(!) be slighty faster, but really, nothing to worry about.

Your B: example shows an anonymous function, which also has no performance impact over the A and C.

jAndy