Unless there is something wrong with my test, when I run this jsfiddle on Chrome I'm getting around 11ms for an $("#id")
selector and 56ms for a $(div#id)
selector.
$(document).ready(function(){
startTime = new Date().getTime();
for (i = 0; i < 10000; i++)
{
s = $("#idC12");
}
$("#idResults").html("c12 by id only time: "+elapsedMilliseconds(startTime));
startTime = new Date().getTime();
for (i = 0; i < 10000; i++)
{
s = $("div#idC12");
}
$("#classResults").html("c12 by tagname#id: "+elapsedMilliseconds(startTime));
});
function elapsedMilliseconds(startTime)
{
var n = new Date();
var s = n.getTime();
var diff = s - startTime;
return diff;
}
http://jsfiddle.net/MhWUc/
That's because $("#id")
internally uses the native document.getElementById function, which uses a map linking from the id to the (unique) element having this id.
Here's the relevant code in jQuery source :
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/
...
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
You'll notice that :
#someId
formNote that this rule is still true outside of jQuery, when defining CSS rules or using document.querySelector
: when you know the id, there is nothing faster than using document.getElementById
(apart a cached element...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With