Good Ways to Improve Jquery Selector Performance

Good ways to improve jQuery selector 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.

Selector for best performance in jQuery?

If all you want is all instances of DOM elements that match .my-class, then I see no reason why you should use anything other than:

$('.my-class')

The others are all more specific selectors and can be used if you want to narrow the selector to more than just $('.my-class').

If you're really trying to fully optimize performance, than using jQuery in the first place is likely not the desired choice as the overhead of jQuery initialization and jQuery objects tends to slow things down. You use jQuery because it's quick to code and offers great cross-browser support and a bunch of useful methods. You don't use jQuery to optimize performance.

If you really want to compare the performance of your four jQuery options, then you will have to design up a representative set of HTML (which has to include lots of other things to be truly representative of a real world situation) and then test each of your selectors in some benchmarking tool like jsperf and run that test in all browsers that you care about and with the versions of jQuery that you will be using and then see if you can come to some particular conclusion.

This smells like an attempt at premature optimization. Write your code first as simply as possible and only spend time optimizing performance when you've actually measured that you have a performance issue and that this is the place in your code where the performance bottleneck is. 99.99% of the time, the performance of a particular selector is not going to make one iota of difference in your code. Code simply and without complication first. In the 0.01% of the time that you actually want to optimize your code, you will probably care so much about performance that you will either pre-cache the list of elements or you will not code it in jQuery in order to avoid the jQuery object setup and overhead.

Here's a jsPerf: http://jsperf.com/jquery-selector-comparison-specificity/4. This shows relatively little difference between the options when tested in the latest versions of Chrome, Firefox and IE. There is a slight bias in favor of the $('.my-class') option.

And for reference, you will find that:

document.getElementsByClassName("my-class")

is as much as 50x faster than any of the jQuery options.

Here's a screenshot of the jsperf results in Chrome:

Sample Image

Conclusions

  1. For normal coding where you haven't proven you actually have a performance issue that you need to spend time optimizing, use the simplest selector that meets your selection objective.

  2. If it's really performance critical, use plain Javascript, not jQuery.

Improve selectors performance with jQuery

It has changed now.

Most of the browsers are implementing :

var matches = document.body.querySelectorAll('div.highlighted > p');

Inside their implementation in javascript.

That's what jQuery uses inside now; It is implementing sizzle.js,
a selector js library that chooses whether to use querySelector or the regular getElementsByTagName function;

For example, for the jquery constructor function $()
if the first argumemt is a string : $(iAmAString),
then if the first letter of the string is a #, jquery will call document.getElementById(iAmAString.substr(0)).
If not it will let sizzle handle whether calling querySelector depending on the browser's compatibility and the complexity of the string.

and lots of other awesome things.

Being the most precise when selecting your element, using base functions and caching your frequently used selectors, will reduce the number of checks when passing through this big chain and/or even circumvent the whole chain.

For some websites, this had the particular effect of generating a unicorn riding kitten effect of awesomeness, what more to say:

the compatibiity support is here
https://developer.mozilla.org/en-US/docs/Web/API/Element.querySelectorAll

What are some quick tips for increasing jQuery performance?

  1. Prefer simple selection first only by ID, and second only by tag name. Selecting by class name or CSS selector requires jQuery to walk the DOM, while ID and tag map to "native" browser DOM functions (getElementById and getElementByTagName).
  2. Cache your jQuery objects as much as possible.
  3. Scope your operations to a root jQuery object. Rather than selecting elements individually, select a common ancestor element and use the find function to find elements within the scope of that elements children. This is really only optimal if you are performing some operations on the common ancestor anyway; otherwise the overhead of finding the ancestor and caching it may outweigh the benefit of scoped traversal.
  4. Don't use $.each(), use for(;;) instead. It's over ten times faster.

jquery increase performance of each function selector

This is my attempt to convert .each() to a for loop:

function populate(){
var myID = $('#thelist span'); //collect all spans as array
for (var i = 0, len = myID.length; i < len; i++) //for loop
{
let myid = myID[i].id; //span at count i in array as number
let url = `importer.php?id=${myid}`;
$.ajax(
{
url: url,
success: function(result)
{
$('#'+myid).html(result);
}
});
})
};

I did obtain a significant increase in performance.

jQuery performance - class selector

Be careful not to get too caught up in these types of issues - micro-optimization can really ruin a project. Not that it isn't good to ponder from time to time, but sincerely, be cautious.

If you still would like to know which of those three are faster, you can setup a quick performance test via http://jsperf.com and give them all three a run against that markup. Fortunately for you, I've saved you the hassle and setup the test myself ;) http://jsperf.com/css-selector-specificity

Results:

                              Ops/Sec
----------------------------+---------+--------+------------
$('.foo > .bar > .target'); | 78,379 | ±6.54% | 65% slower
$('.foo .bar .target'); | 78,499 | ±7.72% | 66% slower
$('.target'); | 213,488 | ±0.39% | fastest

As you can see, the simplest of the three was much faster. Your results will vary from browser to browser. For instance, the above is from Chrome version 23. When I ran this test in Internet Explorer 10, it was even faster, with over 216,000 operations a second.

Performance of jQuery selector

Never prepend a tag name before an id, it’ll slow down the selector.
$('#content') is better than $('div#content')

jQuery starts parsing the selector using a regular expression. If it discloses that the selectors is an id, because it starts with a sharp (#), behind the scenes jQuery will use the JavaScript native getElementById() method, that is very fast.



Related Topics



Leave a reply



Submit