I have a question regarding efficiency of jQuery filtering. I’ve just written quite a lengthy expression and I was wondering if jQuery stops filtering if the current number of matches is 0.
passengers.filter('input.FromDate[value="01/09/2011"]')
.closest('tr')
.filter('input.ToDate[value="08/09/2011"]')
.length;
If after the first filter() call the number of matches is 0 will jQuery continue to search the DOM or will it forego the additional calls and just return 0?
The nice thing about chainable calls with jQuery is that when there are no matches, nothing bad will happen.
When you call
.filterand zero matches have been yielded, you are executing the subsequently chained method calls by definition because they are invoked directly on the returned object (that’s what chaining is).When there are no matches, JavaScript will still invoke each subsequently chained method on each returned object. How much wasted processing happens depends on how the specific method has been implemented.
Demo.
I would expect that most jQuery methods are coded such that nothing drastic happens before the length of the collection has been tested, but you never know.