My PyCharm IDE warns me if I use inefficient jQuery selectors:
As I am a bit nosy I wanted to know “how” inefficient these selectors are. So I compared the inefficient
$("#items tbody");
with the optimized
$("#items").find("tbody");
Here is the test code:
window.onload = function () { test("unoptimized", function () { for(var i = 0; i < 100000; i++){ $("#items tbody"); } assert(true, "Test finished"); }); test("optimized", function () { for(var i = 0; i < 100000; i++){ $("#items").find("tbody"); } assert(true, "Test finished"); }); };
I used the little test framework from the book Adventures of the JavaScript Ninja
The results vary from run to run but the optimized version just takes around 55% of the time which makes it almost twice as fast.
Though the single execution is in the nanosecond range, if you heavily rely on using jQuery, it might be worthwhile to optimize your selector statements.