Search code examples
javascriptjquerycallbackjquery-eventsjsperf

jQuery Event Callback Speed: Anonymous vs. Named Functions


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.


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 :)