Friday, October 7, 2011

jQuery speed test - sibling selector

I'll continue the previous post with a similar one. But this time I tested the sibling selector of jQuery. And as it turned out it is quite interesting but I don't want to kill the joke too early, so let's see that pic:


Well, IE is...slow, so to see things clearer I have removed it from the graph:


Obviously the fastest solution is: jQuery("h1 + h2")

BUT... there are some really interesting things going there. How can it be, that jQuery("h1").siblings("h2") is sooo much slower, than this:

jQuery("h2").filter(function () {
    return jQuery(this).prev()[0].tagName == "H1";
});


If anybody knows the answer, please share it with us!

jQuery speed test - child selector

Selecting child elements with jQuery is not a challange. However selecting it the fastest way is. I did a simple jQuery selector speed test with the latest versions of Firefox, Chrome, Opera and Internet Exporer. The values you see here are in milliseconds per 1000 cycle.

Here is what I got:


Based on the previous chart it seems... well, quite obvious that IE is the slowest and Chrome is the fastest... but returning to the topic... :)

Here are the comparisons of the fastest ways of getting the children elements (the datas from IE are excluded from the test now due to the large difference):

For all child elements the best way is:
jQuery("li > *"). It's:
  • ~29.4% faster than jQuery("li").children()
  • ~86.1% faster than jQuery("> *", li)
  • ~140% slower than li.children()

And for only link elements the best method is:
jQuery("li > a"). It's:
  • ~65.2% faster than jQuery("li").children("a")
  • ~87.5% faster than jQuery("> a", li)
  • ~47.3% faster than li.children("a")

The other thing to observe is that the loops are much faster if you store the base jQuery wrapper object in a variable.