jQuery selector: Why is $("#id").find("p") faster than $("#id p") - javascript

The author of this page: http://24ways.org/2011/your-jquery-now-with-less-suck asserts that the jQuery selector
$('#id').find('p') is faster than $('#id p'), although that presumably produce the same results if I understand correctly. What is the reason for this difference?

Because $('#id').find('p') is optimized to do...
document.getElementById('id').getElementsByTagName('p');
...whereas I'm guessing $('#id p') will either use querySelectorAll if available, or the JavaScript based selector engine if not.
You should note that performance always has variations between browsers. Opera is known to have an extremely fast querySelectorAll.
Also, different versions of jQuery may come up with different optimizations.
It could be that $('#id p') will be (or currently is) given the same optimization as the first version.

It’s browser specific since jQuery uses querySelectorAll when it’s available. When I tested in WebKit it was indeed faster. As it turns out querySelectorAll is optimized for this case.
Inside WebKit, if the whole selector is #<id> and there is only one element in the document with that id, it’s optimized to getElementById. But, if the selector is anything else, querySelectorAll traverses the document looking for elements which match.
Yep, it should be possible to optimize this case so that they perform the same — but right now, no one has. You can find it here in the WebKit source, SelectorDataList::execute uses SelectorDataList::canUseIdLookup to decide whether to use getElementById. It looks like this:
if (m_selectors.size() != 1)
return false;
if (m_selectors[0].selector->m_match != CSSSelector::Id)
return false;
if (!rootNode->inDocument())
return false;
if (rootNode->document()->inQuirksMode())
return false;
if (rootNode->document()->containsMultipleElementsWithId(m_selectors[0].selector->value()))
return false;
return true;
If you were testing in a non-WebKit browser, it’s possible that it is missing similar optimizations.

Related

CSS Selectors performance, DOM Parsing

My question is related to DOM parsing getting triggered, i would like to know why it's faster to use a CSS ID selector than a Class selector. When does the DOM tree have to be parsed again, and what tricks and performance enhancements should I use... also, someone told me that if I do something like
var $p = $("p");
$p.css("color", "blue");
$p.text("Text changed!");
instead of
$("p").css("color", "blue");
$("p").text("Text changed!");
improves performance, is this true for all browsers? Also how do I know if my DOM tree has been re-parsed?
Well, an #id selector is faster than class selectors because: (a) there can only be one element with a given id value; (b) browsers can hold a map id -> element, so the #id selector can work as quick as a single map lookup.
Next, the first option suggested above is definitely faster, as it avoids the second lookup, thereby reducing the total selector-based lookup time by a factor of 2.
Last, you can use Chrome Developer Tools' Selector Profiler (in the Profiles panel) to profile the time it takes a browser to process selectors in your page (match + apply styles to the matching elements.)
An ID selector is faster than a class selector because there is only one element with an ID but many elements could share a class and they have to be searched.
The code below is needlessly parsing the DOM twice, so of course it will be slower:
$("p").css("color", "blue");
$("p").text("Text changed!");
I encourage you to make your own performance tests whenever you have a doubt. You can get more info on how to do that here: How do you performance test JavaScript code?. Once you've tested performance on your own, you'll never forget the results.
In particular, the execution of the $() function on a given jquery selector must obtain the matching DOM nodes. I'm not sure exactly how this works but I'm guessing it is a combination of document.getElementById(), document.getElementsByTagName() and others. This has a processing cost, no matter how small it may be, if you call it only once and then reuse it you save some processing time.

When to use querySelectorAll

In a piece of example code I wrote
var as = toArray(document.getElementsByClassName("false")).filter(function (el) {
return el.tagName === "A";
});
And I was thinking I could replace that with
var as = document.querySelectorAll("a.false");
Now after reading the following facts
Pretend browser support isn't an issue (we have shims and polyfills).
Pretend your not in your generic jQuery mindset of you shall use QSA for getting every element.
I'm going to write qsa instead of document.querySelectorAll because I'm lazy.
Question: When should I favour QSA over the normal methods?
It's clear that if your doing qsa("a") or qsa(".class") or qsa("#id") your doing it wrong because there are methods (byTagName, byClassName, byId) that are better.
It's also clear that qsa("div > p.magic") is a sensible use-case.
Question: But is qsa("tagName.class") a good use-case of QSA?
As a futher aside there are also these things called NodeIterator
I've asked a question about QSA vs NodeIterator
You should use QSA when the gEBI, gEBN, gEBCN do not work because your selector is complex.
QSA vs DOM parsing is a matter of preference and what your going to be doing with the returned data set.
If browser support was not an issue I would just use it everywhere. Why use 4 different methods (...byId, ...byTagName, ...byClassName) if you could just use one.
QSA seems to be slower (...byId), but still only takes a few miliseconds or less. Most of the times you only call it a few times, so not a problem. When you hit a speed bottleneck you could always replace QSA with the appropriate other one.
I've set up some tests for you to mess around with. It appears that QSA is a lot slower. But if you are not calling it that much, it shouldn't be a problem.
http://jsfiddle.net/mxZq3/
EDIT - jsperf version
http://jsperf.com/qsa-vs-regular-js

jQuery(#id).val() vs. getElementById(#id).value

I been searching but I can only find articles talking about one or the other. Which one is better?
I'm making a small web app where performance is not a big concern since there's nothing complex going on.
I considered using jQuery's val() function since maybe it solves some inconsistency I'm not aware of, but getElementById.value IS faster (although the end user won't notice.)
So which one should I use? Is jQuery's non-native method worth the lower performance to gain more compatibility?
The biggest advantage of using jQuery().val() over document.getElementById().value is that the former will not throw an error if no elements are matched, where-as the latter will. document.getElementById() returns null if no elements are matched, where-as jQuery() returns an empty jQuery object, which still supports all methods (but val() will return undefined).
There is no inconsistency when using .value for form elements. However, jQuery.val() standardises the interface for collecting the selected value in select boxes; where as in standard HTML you have to resort to using .options[this.selectedIndex].value.
If you're using <select> elements as well, .value won't work whereas .val() will.
I would not mind about performance of just getting a value. If you want the best performance, perhaps you shouldn't use a library at all.
jQuery does so many nice little error handling things (look below) that I would never write a line of javascript without jquery in a browser again.
First, val works on checkbox groups, selects, gets html, and the
like.
Second, $ lets you use sizzle selectors, so in the future, you can
easily switch between an ID and a CSS path.
Third, your code will be so much easier to read and maintain if you
just use jQuery, that the time you save maintaining your code
outweighs any speedup that you admit your users won't see. Finally,
jQuery is a very popular, very widely used library. They will make
$ and val as fast as they can.
I think using pure Javascript is quicker for the following reasons:
You won't have to learn more than pure js
If you don't want errors, use catch(exeption) (I think...)
You don't have to put in that little extra time to type in the code to initiate jquery
The browser responds quicker if you don't use jquery
Normal js works (in a better way) on checkboxes #johndodo
Thank you for listening to my answer.
I've been looking into the performance differences with this recently and, slightly unsurprisingly, using vanilla JS to grab a value is faster than using jQuery. However, the fallbacks that jQuery provides to prevent errors, like what #Matt mentioned, is very useful. Therefore, I tend to opt for the best of both worlds.
var $this = $(this),
$val = this.value || $this.val();
With that conditional statement, if this.value tries to throw an error, the code falls back to the jQuery .val() method.
Here https://www.dyn-web.com/tutorials/forms/checkbox/same-name-group.php is an implementation for checkboxes, apparently options just need to be named the same with the array brackets notation in the name i.e.: name="sport[]" then yu get the array inJavascript via: var sports = document.forms['demoForm'].elements['sport[]']
I was looking for a selection type field solution without using jQuery and I came across this solution:
The Selection group is an object: HTMLCollection, and it has a lenght method and a selectedOptions property, which allows you to iterate through its label properties to populate an Array with the selected options, which then you can use:
...
vehicleCol = document.getElementById('vehiculo').selectedOptions;
vehiculos = [];
if (vehicleCol !== undefined) {
for (let i = 0; i < vehicleCol.length; i++) {
vehiculos.push(vehicleCol[i].label.toLowerCase())
}
}
...
I'd use jQuery's val(). Shorter code means faster download time (in my opinion).

queryselectorAll usage

I am currently upating my organisations custom JS library and one thing I am looking to introduce is querySelectorAll.
Looking at compatibility it will run in modern browser and for older browsers I will use feature detection:
if (document.querySelectorAll) {
var nodes = context.querySelectorAll(queryValue);
} else {
var nodes = context.getElementsByTagName(queryValue);
}
Are there any considerations that I should be aware of when using this method or is it good for production?
All opinions valued
Main difference between the two is that:
getElementsByTagName
...will return a "live list", and
querySelectorAll
...will not.
Since this seems to be only for selection by tag, I'd probably ditch the qsa, so you can have the live list if needed. I've got a feeling that qsa may be slower in some browsers as well, but haven't tested it.
EDIT:
This test shows a big performance difference between the two in Chrome 13.

Filtering elements out of a jQuery selector

I have a page that selects all the elements in a form and serializes them like this:
var filter = 'form :not([name^=ww],[id$=IDF] *,.tools *)';
var serialized = $(filter).serialize();
This works, unless the form gets around 600+ elements. Then the user gets s javascript error saying that the script is running slow and may make their browsers unresponsive. It then gives them the option to stop running the script.
I have tried running the filters separately, I have tried using .not on the selectors, then serializing them, but I run into one of two problems. Either it runs faster without the error, but also does not filter the elements, or it does filter the elements and gives me the slow script error.
Any ideas?
With 600+ elements this is going to be dead slow. You need to offer Sizzle (jQuery's selector engine) some opportunities for optimisation.
First, consider the fact that jQuery can use the natively-supported querySelectorAll method (in modern browsers) if your selector complies with the CSS3 spec (or at least to the extent of what's currently supported in browsers).
With your case, that would mean passing only one simple selector to :not instead of 3 (1 simple, 2 complex).
form :not([name^=ww])
That would be quite fast... although you're not being kind to browsers that don't support querySelectorAll.
Look at your selector and think about how much Sizzle has to do with each element. First it needs to get ALL elements within the page (you're not pre-qualifying the :not selector with a tag/class/id). Then, on each element it does the following:
(assume that it exits if a result of a check is false)
Check that the parent has an ancestor with the nodeName.toLowerCase() of form.
Check that it does not have a name attribute starting with ww (basic indexOf operation).
Check that it does not have an ancestor with an id attribute ending in IDF. (expensive operation)
Check that it does not have an ancestor with a class attribute containing tools.
The last two operations are slow.
It may be best to manually construct a filter function, like so:
var jq = $([1]);
$('form :input').filter(function(){
// Re-order conditions so that
// most likely to fail is at the top!
jq[0] = this; // faster than constructing a new jQ obj
return (
!jq.closest('[id$=IDF]')[0]
// this can be improved. Maybe pre-qualify
// attribute selector with a tag name
&& !jq.closest('.tools')[0]
&& this.name.indexOf('ww') !== 0
);
});
Note: that function is untested. Hopefully you get the idea...
Could you maybe just serialize the whole form and do your filtering on the backend? Also, why-oh-why is the form growing to 600+ fields?
use the :input selector to only select applicable elements..

Categories

Resources