Which one is faster?

Hi all

It’s been quite some time that I wonder if it makes any difference in speed to use one of those ($ in JQuery or Mootools) :

$(‘div#SomeId’) vs $(‘SomeId’)

and also in CSS :

#SomeId {} vs div#SomeId{}

and

.SomeClass {} vs div.SomeClass {}

Do you think it makes any difference at all ?

It will definitely make a difference, but I’m guessing only fractions of a millisecond.

With div.something for instance. It may vary but first the engine would find all elements with a class of ‘something’, it would then loop through those found elements checking the nodeName attribute to filter out the ones that match ‘DIV’.

Obviously with just ‘.something’ you can simply use the built in getElementsByClassName when available. One procedure.

Regards div#idname. Given that you should only have one id of a specific name on the page you should be able to ignore the ‘div’ in div#idname and just getElementById. However that’s the theory and I think most engines will do the same as the tag with className procedure and filter out found elements.

As I say fraction of millseconds difference, and that’s also not taking into account any caching that is built into the engine.

Well that’s my understanding:)

RLM

I can’t answer the javascript question but in css div.class is slower as CSS works from right to left.

.SomeClass is matched and the routine ends.

With div.SomeClass the .SomeClass is matched and the browser then has to go and match the Div that is attached to it hence doubling the work.

More info here:

Simplifying CSS Selectors | High Performance Web Sites

And a funny one here.

As mentioned above in most cases the speed difference on normal sites will be negligible unless you have gone overboard with descendant selectors etc.

I like those links Paul. :slight_smile:

The only time I’ve needed to do something like #someid #anotherid { … } is when I’ve needed something to be a lot more specific. It probably indicated bad CSS design!

When using jQuery, it’s also very useful to provide a context. Example:


$('#someDiv .something li span.note');

var someDiv = $('#someDiv');
$('.something li span.note', someDiv);

If someDiv is going to be used again, then the second option is a lot better. It saves jQuery from ever having to find #someDiv again, and it makes the process of finding things inside someDiv faster.

It pains me when I see the results of jQuery expressions not being cached, and then being repeated over and over again, e.g.:

$('#myDiv .something p').css('height','10px');
$('#myDiv .something p').click( ... );
$('#myDiv .something p').mouseover( ... );

// etc.

If someDiv is going to be used again, then the second option is a lot better. It saves jQuery from ever having to find #someDiv again, and it makes the process of finding things inside someDiv faster.

I’m writing a selector engine at the moment(badly I hasten to add). That’s v interesting. I’ve got a pretty basic after thought of a cache implentation which just caches the results and the selector. I had been wondering whether it was feasible to cache in parts as the search is being processed, but just making good use of the root solves that.

Also interesting ( for me anyway) to see what’s returned from $(‘selector’). A test on a simple list.


var x = $('ul');
var y = $('li', x);
console.dir(y);

0: li
1: li
.
.
6: li
context : Document
lenght : 7
prevObject : [ ul ]
selector : 'ul li'

I’m starting to see the advantages of returning an array like object.

A quick experiment, which returns a custom array like object.

function test(selector){
  [].push.apply(this, [].slice.call(document.getElementsByTagName(selector)));
}

var y = new test('li');
console.dir(y);

Thanks

RLM

This is what I use:

function $(str, el, arr) {
  var res = Sizzle(str, el);
  return res.length > 1 || arr ? res : res[0];
}

I use Sizzle (the selector engine in jQuery). Sizzle returns an array of DOM elements. My function returns the first item if there’s only one, unless I specify using the arr attribute that I want an array even if there’s only one item. Makes it easy to do stuff like this, knowing I’m working with an actual DOM element rather than some other object:

$('span.caption', li).firstChild.nodeValue = data;

Thanks for the answers people.

So, for CSS it’s clear that as we KNOW it parses from right to left, any extra step will demand more processing.

Btw, i know this has been widely debated, but right-to-left for CSS seems counter intuitive for developers.

Come on, who ever replaced “#div a” by adding a class to every single link in DIV ? seriously …

Regarding JS, there doens’t seem to be a clear consensus. Looks like there may be a difference between the selector engines … (btw jquery is not the only one out there).

Instead of doing that in jQuery, you could improve performance by making use of the context selector instead:


$('a', '#div')

Thanks paul, but the fact is, I’m not even using Jquery at all :wink:

It matters not whether you are using jQuery or not, it is a useful technique that can be learned from and applied so as to help speed up your searching.

It’s always faster to search for the A elements from within a more confined context, than it is to search for all of the A elements on the page and then to filter through them afterwards.

Historically, it’s a technique that goes back at least to the getElementsByClassName functions.

function getElementsByClassName(className, tag, elm) {

Where elm is for the context within which to search.

I use Sizzle (the selector engine in jQuery). Sizzle returns an array of DOM elements. My function returns the first item if there’s only one, unless I specify using the arr attribute that I want an array even if there’s only one item. Makes it easy to do stuff like this, knowing I’m working with an actual DOM element rather than some other object:

That makes sense. I was tempted to go down the route of using sizzle or sly etc. Would have been the sensible thing to do. Mine has a get method attached which does return an array. I could add the length test to account for single nodes though.

So, for CSS it’s clear that as we KNOW it parses from right to left, any extra step will demand more processing.

Btw, i know this has been widely debated, but right-to-left for CSS seems counter intuitive for developers.

Come on, who ever replaced “#div a” by adding a class to every single link in DIV ? seriously …

Regarding JS, there doens’t seem to be a clear consensus. Looks like there may be a difference between the selector engines … (btw jquery is not the only one out there).

There are two approaches in Javascript(among others) which is bottom up or top down.

Top down works left to right through the selector, and the bottom up right to left working it’s way up through parent nodes etc.

Top down is quicker and would seem like the easy choice, but there is a down side and this is covered in Javascript ninja.

Example.


<div>
  <div>
    <span></span>
  <div>
</div>

Selector 'div span'.

The top down(left to right) firsts look for div tags and come up with two elements.

Those found elements will then each be passed back to the search but this time as the root of the next search. (Does that make sense?)

This time round the search will find a span tag on each of the found div elements(root elements).

The end result when all is returned is that you end up wrongly finding two identical span tags.

One way around it is to add temporary unique identifiers to the found elements, and that way filter out duplicates.

Another way is to go with the bottom up(right to left) approach. I don’t know but this might expain css’s logic.

Cheers

RLM

Of course that would be silly if all (or most) a elements were to be styled the same. However I often see this:

#outer p{}

Then almost every other p element p element in the page needs the id put in front to win out :

#outer p.special ()

It’s all about to doing the right thing at the right time and planning ahead.

Sometimes speed of execution loses out to cleaner maintable code and in most site it won’t matter much either way (as far as css is concerned).

There are some though who promote just using classes but they got very short shrift [URL=“http://www.sitepoint.com/forums/css-53/object-oriented-css-uses-learning-newbie-740553.html”]in this thread.

Thanks Paul O’B !