Another look at jQuery Performance: combining elements and IDs

April 23, 2010 by aaron
Another look at jQuery Performance: combining elements and IDs

A question that came up in regards to jQuery Performance was: is it faster to define the type of element before you set the ID. Basically, is jQuery('textarea#content_box') better than jQuery('#content_box')? The thinking is that because the latter is more specific, the parser has to do less work to find the element. But this is wrong and ignores what actually happens in the jQuery code. If you were writing CSS, then yes, it would be faster to define the element type first, but for JavaScript, defining the element type just adds more work for jQuery.

Why shouldn’t you define the element type?

So even though popular opinion says yes, the real answer is an emphatic no. You should never supply parent elements or element types when defining the ID of an element. Why? The ID of an element is supposed to be unique. While sometimes bad programing styles or unfriendly widgets can cause problems, the ID should always be unique, so there is only one #content_box and it is always going to be a textarea.

What’s the difference?

If you have read the longer post on profiling jQuery, you’ll notice that the fastest method to find any element is to call the #ID of the element directly. Any other call requires jQuery calling Sizzle and parsing the string.

If you use just the ID of an element, it won’t need to load sizzle and can grab it immediately using the built in JS function getElementById('content_box');. The difference of these two expressions is staggering and as my post on profiling JavaScript demonstrated, the difference is an order of magnitude.

comments powered by Disqus

Do you want to get in touch?

Let us know what you want to create.

Contact Us