Is there any performance difference implication for the 2 syntax below?
$(“span.foo”)
$(“.foo”)
Someone told me the first one would merely search span
whose class is foo
while the second would search among all elements.
Is there any performance difference implication for the 2 syntax below?
$(“span.foo”)
$(“.foo”)
Someone told me the first one would merely search span
whose class is foo
while the second would search among all elements.
If you are looking for a performance related issue, it is always better to benchmark the different solutions to see which one is better.
They both may have different results bases on the markup.
But if you have only span
's with the class foo
then the second one will be faster.
The reason could be in the first case it will first load all span's in the document then filter them with the class foo
while the second one will you the native getElementsByClassname
to fetch the elements.
Have a look at this jsperf benchmark
Who ever told you that is correct.
Looks like it is about a half a second(Firefox, Chrome is less than that) when selecting on two elements over 100,000 iterations.
var start, end, i;
start = new Date();
for(i = 0; i < 100000; i++){
$("span.foo");
}
end = new Date();
$("span.foo").html(end - start);
start = new Date();
for(i = 0; i < 100000; i++){
$(".foo");
}
end = new Date();
$("div.foo").html(end - start);
I'm sure you can imaging that selecting on a larger amount of elements would certainly take longer. You likely won't select 100,000 times either, but as websites get larger javascript performance can be one of the largest factors, jQuery's context and selectors can make that much more efficient.
Also, you may be selecting elements that you don't want if you only want to apply functions to spans with a class of "foo"