Check out this test:
http://jsperf.com/delegate-on-vs-bind-5
What I did was delegate the child with a given parent and delegate another event to the child directly. Testing (at least in Chrome) seems to indicate that the delegating method is significantly faster than the direct binding method. This really goes against everything I’ve read about jQuery and also what I believe to be its intent. Is my test mistaken or should we really just be using the delegation method? Note that the parent is not even that close of an ancestor to the child.
This fiddle also confirms that the events are appropriately triggered with this DOM and JS:
Thoughts?
EDIT: To clarify, my specific question is why is the delegation method (traditionally supposed to be slower) so much faster than the bind method (supposed to be faster) in this test?
- Did I just write a bad test?
- Is jsperf benchmarking screwed up?
- Should we really just be using the delegation method all the time since it’s superior?
Real answers will follow I’m sure, but you asked for thoughts.
My thought is that with modern systems it is Virtually Impossible to consistantly predict how a given construct will effect performance.
You will get the explanation for this one, and after thinking about it for a while and fiddling with it you will believe it (Or maybe it will be found to be a measuring error), but in the long run it won’t give you any real insight into how to code better. Furthermore on a different browser/platform/version/day of the week it will happen to work differently.
The problem is that if there is a construct they expect you to use a lot (because that’s how people generally code), they will optimize it first and it will probably perform faster. The results of this is that the performance improvements done at the levels beneath your code will typically improve your well-written code over code your hand-optimized code.
This means you should NEVER code for performance, code for clarity and DRY, period. If you do so and hit a barrier where some customer or manager judges it too slow (Get Performance Requirements!), then consider recoding it with before-and-after measurements on each platform of course. Do comparisions and ensure that the “Optimized” solution is actually worth the lack of clarity and actually meets the requiremetns. Document WHY you did this in the code so someone else doesn’t come along and fix what looks like your crappy coding style later.