2009/10/14 James <james.gp....@gmail.com>: > > Unless your DOM tree is huge and you're trying to select something > massive in one go, the performance difference between a simple jQuery > ID selector (e.g. $("#myID")) vs. a native getElementById selector > should be very negligible, because jQuery uses that same native > selector. >
"Negligible" is a bit strong; an examination of the jQuery selector code shows that, although it is well optimised for the simple ID selector, it will nonetheless do the following for $("#foo"): 1. do a logical OR detecting the presence of a selector, 2. test for the presence of a nodeType property on the selector, 3. branch over an if clause (see step 9) when that test fails, 4. compare the type of the selector with "string" and enter an if clause, 5. execute a match using a regular expression, 6. test that the match array is not null and that it has a value at a specific position in the match array and that no context argument was passed, 7. test the same position in the array and branch to an else clause, 8. finally execute getElementById, then recursively call itself causing it to repeat steps 1 and 2, where it will enter the if clause, 9. set a few properties on itself, 10. return itself from the recursive call, 11. return the value received from the recursive call to your code. Clearly that's quite a bit of overhead; if all you actually need is a reference to the DOM element itself, using getElementById directly is always going to be faster. Even if you want the DOM element to be wrapped in the jQuery object, it is much more efficient to replace var foo = $("#foo"); with var foo = $(document.getElementById("foo")); as that will get to step 2 above, drop into the if clause (step 9) and return, avoiding a RegExp match, assorted bits of logic and property testing, and a recursive function call. Regards, Nick. -- Nick Fitzsimons http://www.nickfitz.co.uk/