Performance wise which one is better:
$(".myclass").eq(0)
OR
$("a.myclass")
Note: If there is only one <a>
tag having .myclass
.
Performance wise which one is better:
$(".myclass").eq(0)
OR
$("a.myclass")
Note: If there is only one <a>
tag having .myclass
.
The second - always use tag names when you can (see rule 2 of the jQuery performance rules).
The second, because it can use the browser's document.getElementsByTagName()
function that is implemented in C/C++, rather than Javascript.
Also, if there is only a single a
with .myclass
consider putting an id on it and doing $('#myid')
. Fetching by id is the fastest way. It uses document.getElementById()
which, again, is implemented in C/C++.
For more, see Paul Irish's Anti-patterns starting at about slide 19.
Always descend from an ID if you can. Be more specific on the right and more general on the left.
There's a jquery based speed profiler out there that would allow you to test this to see the actual speed differences, but I'm having trouble finding it...
These things are easy to profile using firebug.
console.profile();
jQuery('#id');
console.profileEnd();
Sometimes it depends upon your dom / which browser your targetting etc etc rather than relying on 'best practise'. Always profile locally to see what works best.