Question

This is kind of a random question, but I was wondering why a named callback was performing worse, for a click event, relative to an anonymous function.

Here is the link to the JSPerf tests I ran in Firefox and Chrome on Mac.

I guess my assumption was that named callbacks would always perform better. For instance, when using .each the named callback is slightly faster.

Thanks for your time!

Edit I edited the .each JSPerf test because (a) I wasn't testing what I meant and (b) I'm trying to mimic events more so.

Edit 2 My test setup was incorrect from the start as @Esailija points out below. This question is somewhat pointless but at least it might help someone with JSPerf testing.

Was it helpful?

Solution

The jsperf is broken because you accumulate event handlers across test boundaries. In other wrods, whatever test is run first will be the "fastest".

And the whole premise of the test is ridiculous, there is no difference between a function that has a name and a function that doesn't have a name if everything else is equal. You will only see a difference when you are setting up jsperf incorrectly. When you constantly get equal results for them then you know that you set it up correctly - but you would know this already from common sense :)

OTHER TIPS

The anonymous function is passed as an argument, so to resolve its reference, the scope chain does not reach all the way back to the parent function that created it - it only exists as an argument. On the other hand, to resolve the reference to the named function, the scope chain is followed all the way back to the parent function closure where the named function was created.

Edit: I tried to prove this, but it seems as if the anonymous function does not actually get resolved faster - http://jsperf.com/scope-chain-anonymous-function

Edit: If you call a.off(); to remove any event handlers, the named function will be just as fast or faster than resolving the anonymous function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top