As I become more and more obsessed with Quora, I’m finding more and more questions that I answer seem to feel right as standalone blog posts. The latest even includes an interesting discovery: What’s the cleanest way to intentionally and reliably return a jQuery object that selects nothing?
There were two answers already posted to the question, suggesting the following methods to achieve an empty jQuery set:
While the previous answers will definitely return a jQuery object that selects nothing, neither of them is best choice for performance. The answer is actually on line 79 of the jQuery source, it’s the first condition that jQuery ever evaluates:
I thought it might be beneficial to benchmark these against the suggestions posted above; here is the test files and results: http://gist.github.com/555527
I added my own $(false) technique to the equation as well; I’m pleased with the results:
In conclusion, I can say with complete confidence that $(false) is the fastest and that $(‘null’) is the definitely the worst, as it will attempt to look through entire document, coming up empty handed, but exhausting itself.
Thanks to James Padolsey for mentioning
new jQuery.fn.init, which is clearly the winner - I’ve added it’s scores to the test results above.