I was recently asked whether it would be ‘better/quicker’ to replace
$('ul li a')
My initial response was to warn that these two lines of code don’t actually do the same thing. As explained in the jQuery API reference for the descendant selector, the suggested replacement would (for example) pick up
li elements that were descendants of
ul elements – and ‘descendants’ can include grandchildren and so on, not just children.
In this case, the structure of the page meant that this wasn’t an issue. I was surprised, though, to find an article posted earlier this year by Rob Tarr showing that in fact the existing code could be quicker than the suggested replacement. The article, jQuery Selector Performance Testing, shows the results of performance tests of chaining
find method calls, chaining
children method calls, and chaining selectors. In the tests, chaining the method calls was significantly faster than chaining the selectors.
So in this case the existing code was probably the ‘better/quicker’ option after all.