Tuesday, June 16, 2009

Selecting the fastest selector for jQuery using Firebug Profile

Today I needed to select all the h3's within a div and set a margin-top property on all items in the returned set except the first.

I came up with a few ways to return the results I was looking for (here are some jQuery examples):

$("#div h3").slice(1);

$("#div h3:not(:first)");

$("#div h3:gt(0)");

I've been reading a lot about how your selection can be optimized based on how you structure your query. So I ran each query through Firebug Profile to see which selector query was the fastest. Load the page, click on the "Profile" button at the top, run your query in the console, click the "Profile" button again to stop the profile.  You'll get the time it took to execute that statement.  Here are the results for each:

$("#div h3").slice(1); 3.305ms

$("#div h3:not(:first)"); 0.705ms

$("#div h3:gt(0)"); 2.347ms

It's clear from my testing that the second query is 2-3 times faster then the rest for my page and my specific uses.  Your specific profile times may vary based on HTML structure and selector query. So it's always good practice to test the speed of your selector if there is more then one way to get your results so that you are using the most efficient selector for your situation. 
Tuesday, June 16, 2009 10:27:55 AM (Eastern Standard Time, UTC-05:00)
Wow, that's pretty awesome - I would've just guessed that they were all close in speed.
Tuesday, June 16, 2009 10:33:34 AM (Eastern Standard Time, UTC-05:00)
You cant just take the result from FF. You really need to opitize for your largest audience which I suspect is one of the ie's. I bet the results are different there!!
redsquare
Tuesday, June 16, 2009 10:35:29 AM (Eastern Standard Time, UTC-05:00)
@redsquare - good point.
Tuesday, June 16, 2009 1:40:13 PM (Eastern Standard Time, UTC-05:00)
I was going to mention the same thing about browser differences, but redsquare beat me to it. Also, considering that even the slowest selector is only 3 milliseconds, the difference is probably going to be imperceptible.

(feel free to delete this if it's a duplicate post. not sure what happened the first time I tried commenting)
Monday, August 10, 2009 3:38:59 AM (Eastern Standard Time, UTC-05:00)
Excuse me. A little government and a little luck are necessary in life, but only a fool trusts either of them. Help me! It has to find sites on the: preferred window coverings. I found only this - <a href="http://indipendentifiorenzuola.it/Members/Coverings">electric window Coverings</a>. This house is spotless shows extremely well. Lamp shade tutorial the basic method and coolie. Waiting for a reply :cool:, Lorraine from Africa.
Comments are closed.

Blog Posts by:

Currently Viewable:

The Official jQuery Podcast

with Ralph Whitbeck & Rey Bango

You can subscribe to the show in iTunes or via the raw RSS feed

My Twitter Updates

View Twitter Page