optimizing jQuery Selectors - Which is faster? - javascript

Are selectors or functions faster in jQuery? Example:
$('#something div.else'); // find multiple divs with class .else
or
$('#something').children('div.else');
I'm trying my best to optimize a page with hundreds of returned elements that seems to hang on a certain crappy computer here in the office (that must use Internet Explorer ::shudder::).

Well in this case, the second's faster, but, they're not equivalent. The first finds any descendant div.else, the other finds only direct children that are div.else.
It depends on your DOM as to which is faster, the equivalent of the second would be this:
$('#something > div.else');
This uses the child selector. They should be very, very close, and in any case, I doubt a selector descending from an ID is your problem area, I think you'll find the vast majority of your time in JS is spent elsewhere.
For diagnosing speed issues, get a profiler, for IE specifically there's a fantastic free one called dynaTrace AJAX Edition. Grab it, follow the short tutorials on their site...you'll find where your pain areas in IE are pretty quickly.

Although I haven't checked with the jQuery code, I think the difference should be negligable between your two examples - although the first one should run a little faster.
The problem with old IE versions is that they do not support a native way to fetch items based on class names. In this case, jQuery has to execute a regulra expression on each class attribute of each element contained.
If it is possible in your case, you might gain quite a lot performance when being able to select on an unusual tagname:
$("#container blockquote.else")
and ideally,leave away the class name.
EDIT: just saw the answer from Nick and he's right, the scond one only has to check the direct children. The equivalent first one would be:
$("#container > div.else")

In your specific example, your first example of
$('#something div.else');
gets optimized through Sizzle (which is delivered within the jQuery lib) into
$('#something').find('div.else');
without that optimization, it would be slower, since the selector engine sizzle does work from right to left. So, it would match all divs with the class else and would then check which of those has #something as parent.
edit
The Sizzle optimazation is slower
anyway, since it took a while until
that task is completed and some
functions are called on the way
In general, using jQuery functions is a lot faster. For instance jQuerys .eq() function will use an array slice to reduce a wrappet set of jQuery objects, whereas :eq() selector will invoke sizzle.
If in your example, div.else elements are direct children of #something, .children() will beat .find() since .find() will also lookup all descendants (and their childs).

If I understand correctly you need the fastest way to get #something div.else in IE6. Since jQuery uses Sizzle, the way it will find that is first find all div's, then filter by the ones with the else class, and has an ancestor with the #something id.
Your second example will be faster if it contains few children, slower if it contains many.
A suggestion you could try would be to use another tag type instead of div, one that isn't used in your page, say blockquote. Just reset it's styles with css so it looks like a normal div, then change your selector to #something blockquote.else which should be tons faster.

Related

jQuery + VanillaJS achieve fastest selection method

I'm developing an application with jQuery and i was wondering what is the fastest method to select an element with jQuery, there are hundreds of elements in this web page and each one has an unique id, and i'm doing this:
$("#main-container").addClass("col-lg-12");
i know that's the slowest approach to do it, so i think the main question is what is faster?
// 1
$("#main-container").addClass("col-lg-12");
// 2
$(document.getElementById("main-container")).addClass("col-lg-12");
// 3
$(document.querySelector("#main-container")).addClass("col-lg-12");
Use something like http://jsperf.com/ for performance checks
Looks like $(document.getElementById("main-container")).addClass("col-lg-12"); is the fastest of those 3
http://jsperf.com/buttsnanananannana/6
If you're pananoid about performance though, you probably shouldn't be using jQuery. You can do this instead: document.getElementById('main-container').classList.add('col-lg-12')
If you're really interested about performance you shoulnd't use jQuery. That said if you want to have the fastest selection method you should be using the most JavaScript native specific selection method you can, like:
document.getElementById()
document.getElementsByTagName()
document.getElementsByClassName()
I understand that it is really easy to use the most generic ones:
document.querySelector()
document.querySelectorAll()
The thing with the last ones is that they're going to spend time looking if your selector is a class or id, and/or if it's inside another elements.
However my recomendation for you is to use the specific ones every time you can, and if you want to use the jQuery thing and wrap them with it, well that is up to you.
There is a jsPerf for you:
As you can see in this chart, document.getElementById() is way faster than document.querySelector(). But when is wrapped into $() is like nine times slower than normal
$(document.getElementById("main-container")).addClass("col-lg-12"); will be the fastest selector out of the three that you've provided.

Which of these jQuery JavaScripts will have better performance?

I have sections with headers. Clicking the header collapses and expands the section below it. A class is also applied or removed to the header for styling purposes. There are 9 of these sections and headers.
$('.header').click(function() {
$(this).toggleClass('open');
$(this).next().slideToggle();
});
Im trying to improve performance for mobile devices. I dont mean page loading times, rather the smoothness of the animation and delay after touching the header before the annimation fires.
Ive read that using IDs is faster than Classes. How much faster will the following be? (note, it would need to be repeated 9 times and ive shown the first 2). Im also assuming using an ID is faster than traversing the DOM with .next(), how much difference will this make?
$('#header1').click(function() {
$(this).toggleClass('open');
$('#section1').slideToggle();
});
$('#header2').click(function() {
$(this).toggleClass('open');
$('#section2').slideToggle();
});
Note, I know its a bit of a crutch but I want to use jQuery not plain JavaScript. The jQuery library will be loaded anyway as its used elsewhere on the site. Thanks
It doesn't matter at all. While ID lookups are indeed the fastest, modern browsers have optimized selector-based lookups so all of them are pretty fast unless you do something that requires iterating over the whole document (such as a [someattribute] selector).
However, $('.header') saves you from repeating code and thus is the way to go. Besides that, it's more readable - in the second example you don't even know where the element it affects is without looking at the DOM.
So, instead of trying to optimize what doesn't need to be optimized, keep your code clean and maintainable!
The second method will be marginally quicker, however the slight gain will be negated by the ugliness and unmaintainability of the code.
Use the first option.
Technically:
The ID reference method is a far faster DOM lookup in browsers that don't support getElementByClassName. But that's offset by having to parse twice the amount of code and apply two click handlers. .live() may be faster still as it only binds to the body and does the lookup later.
Practically:
Very negligible difference. This is micro optimization territory. There are probably much bigger factors of speed in your code than this.
An id as a selector is quicker, but for maintainability do you really want that duplicated code?

Is there an efficiency difference between finding by id and finding by class with JavaScript/jquery?

Is there an efficiency difference between finding by id and finding by class with JavaScript/jquery?
Is one better than the other? If so is it because indexes of ID or Class are made in the DOM somewhere?
Does it end up not mattering much?
Finding by ID is always faster, no matter where (getElementById(), $('#id'), or even in regular CSS).
Since ID's are unique per page, they're much faster to find.
In addition, when using $('#id'), jQuery will map that back to the built-in getElementById(), which is the fastest way to query the DOM.
Well, logically speaking, an ID would be more efficient, as there is (should be) only one of it, so once it finds it, it will stop searching. However I am not familiar with the jQuery source, I don't know how it actually works, that's from a logic perspective.
For most browsers, the difference in speed between searching by id and searching by class name depends on how many elements have a given class. At best, there will be only one such element, and the search speed ought to be the same. At worst, there are a bazillion elements with a given class. Typically, though, you shouldn't have to worry about the speed of searching through 10-20 elements containing the same class.
A critical caveat, though: MSIE <= 8 has no native getElementsByClassName, so jQuery has to fall back to a full DOM tree search unless, e.g., the element name of the wanted element is also provided. Even then. $('div.myclass') may not be much help if your document is large and exceedingly div-happy. Benchmarking is really the only way to find out.

JavaScript for Searching an Element's Specific Ancestor Like in XPath?

Searching downwards from a given node works wonderfully and crossbrowser-compatible with Javascript functions querySelectorAll() and querySelector().
This functions allow to state any CSS3 selector for searching child elements. As far as I have understood, there is no way to search parental nodes: W3 CSS3 Selectors
I'd like to search parent nodes too like possible with XPath axe ancestor.
Something like (XPath):
select="./ancestor::*[#attributex='xxx'][2]"
Note that I haven't tried out the above XPath expression, and I'm not sure if it only selects the nearest ancestor, but that was my intention.
I know that I could directly use XPath in JavaScript, but I'd rather avoid it as I don't know about 1) browser compatibility and 2) searching downwards works fine with querySelector/All().
I'd also rather avoid some for-loop searching one .parentNode after the other and compare its .getAttribute("attributex") with the searched one.
Any ideas how to accomplish this with cross-browser-compatible JavaScript?
I think you would appreciate jQuery's parents([selector]) method. For sure it take advantages in terms of compatibility. Take a look at http://api.jquery.com/parents/

Good ways to improve jQuery selector performance?

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I'm looking for any way that I can improve the selector performance of a jQuery call. Specifically things like this:
Is $("div.myclass") faster than $(".myclass")
I would think it might be, but I don't know if jQuery is smart enough to limit the search by tag name first, etc. Anyone have any ideas for how to formulate a jQuery selector string for best performance?
There is no doubt that filtering by tag name first is much faster than filtering by classname.
This will be the case until all browsers implement getElementsByClassName natively, as is the case with getElementsByTagName.
In some cases, you can speed up a query by limiting its context. If you have an element reference, you can pass it as the second argument to limit the scope of the query:
$(".myclass", a_DOM_element);
should be faster than
$(".myclass");
if you already have a_DOM_element and it's significantly smaller than the whole document.
As Reid stated above jQuery is working from the bottom up. Although
that means $('#foo bar div') is a
lot slower than $('bar div #foo')
That's not the point. If you had #foo you wouldn't put anything before it in the selector anyway since IDs have to be unique.
The point is:
if you are subselecting anything from an element with an ID then select the later first and then use .find, .children etc.: $('#foo').find('div')
your leftmost (first) part of the selector can be less efficient scaling to the rightmost (last) part which should be the most efficient - meaning if you don't have an ID make sure you are looking for $('div.common[slow*=Search] input.rare') rather than $('div.rare input.common[name*=slowSearch]') - since this isn't always applicable make sure to force the selector-order by splitting accordingly.
In order to fully comprehend what is faster, you have to understand how the CSS parser works.
The selector you pass in gets split into recognizable parts using RegExp and then processed piece by piece.
Some selectors like ID and TagName, use browser's native implementation which is faster. While others like class and attributes are programmed in separately and therefore are much slower, requiring looping through selected elements and checking each and every class name.
So yes to answer your question:
$('tag.class') is faster than just $('.class'). Why?
With the first case, jQuery uses the native browser implementation to filter the selection down to just the elements you need. Only then it launches the slower .class implementation filtering down to what you asked for.
In the second case, jQuery uses it's method to filter each and every element by grabbing class.
This spreads further than jQuery as all javascript libraries are based on this. The only other option is using xPath but it is currently not very well supported among all browsers.
Here is how to icrease performance of your jQuery selectors:
Select by #id whenever possible (performance test results ~250 faster)
Specify scope of your selections ($('.select', this))
I'll add a note that in 99% of web apps, even ajax heavy apps, the connection speed and response of the web server is going to drive the performance of your app rather than the javascript. I'm not saying the you should write intentionally slow code or that generally being aware of what things are likely to be faster than others isn't good.
But I am wondering if you're trying to solve a problem that doesn't really exist yet, or even if you're optimizing for something that might change in the near future (say, if more people start using a browser that supports getElementsByClassName() function referred to earlier), making your optimized code actually run slower.
Another place to look for performance information is Hugo Vidal Teixeira's Performance analysis of selectors page.
http://www.componenthouse.com/article-19
This gives a good run down of speeds for selector by id, selector by class, and selector prefixing tag name.
The fastest selectors by id was: $("#id")
The fastest selector by class was: $('tag.class')
So prefixing by tag only helped when selecting by class!
I've been on some of the jQuery mailing lists and from what I've read there, they most likely filter by tag name then class name (or vice versa if it was faster). They are obsessive about speed and would use anything to gain a smidgen of performance.
I really wouldn't worry about it too much anyway unless you are running that selector thousands of times/sec.
If you are really concerned, try doing some benchmarking and see which is faster.
Consider using Oliver Steele's Sequentially library to call methods over time instead of all at once.
http://osteele.com/sources/javascript/sequentially/
The "eventually" method helps you call a method after a certain period of time from its initial call. The "sequentially" method lets you queue several tasks over a period of time.
Very helpful!
A great tip from a question I asked: Use standard CSS selectors wherever possible. This allows jQuery to use the Selectors API. According to tests performed by John Resig, this results in near-native performance for selectors. Functions such as :has() and :contains() should be avoided.
From my research support for the Selectors API was introduced with jQuery 1.2.7, Firefox 3.1, IE 8, Opera 10, Safari 3.1.
If I am not mistaken, jQuery also is a bottom up engine. That means $('#foo bar div') is a lot slower than $('bar div #foo'). For example, $('#foo a') will go through all of the a elements on the page and see if they have an ancestor of #foo, which makes this selector immensely inefficient.
Resig may have already optimized for this scenario (it wouldn't surprise me if he did - I believe he did in his Sizzle engine, but I am not 100% certain.)
I believe that selecting by ID first is always faster:
$("#myform th").css("color","red");
should be faster than
$("th").css("color","red");
However, I wonder how much chaining helps when starting with the ID? Is this
$("#myform").find("th").css("color","red")
.end().find("td").css("color","blue");
any faster than this?
$("#myform th").css("color","red");
$("#myform td").css("color","blue");

Categories

Resources