5

JQuery selectors - By order of speed

 3 years ago
source link: https://www.codesd.com/item/jquery-selectors-by-order-of-speed.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JQuery selectors - By order of speed

advertisements

I found a article regarding this a year ago but cannot find it now and all other articles I find aren't quite complete.

What I want is to build a definitive list of the quickest ways to select elements in jQuery

As Far as I understand it, If I had the following

<body>
  <div id="container">
    <ul class="count">
      <li>One</li>
      <li>Two</li>
      <li class="selected">Three</li>
    </ul>
  </div>
</body>

In order of speed (fastest to slowest) Selecting by Id:

$('#container')

Select by Element:

$('div')

Select by class with help of element

$('ul.count')

Select by Part of Element Id with help of element (in this case ends with)

$("div[id$='tainer']")

Select by class

$('.count')

Select by Part of Element Id (in this case ends with)

$("[id$='tainer']")

Is this in the correct order of speed and have I missed any?

Thanks


performance of selectors depends on several things. browser is the main factor, with sizzle/querySelectorAll/jsengine, and jquery version which use them. Basically, jquery improves performances at each version, and does a good job to chose the best available method according to the browser.

Any kind of updates in the browser, js engine, or jquery itself can raise a new "best performer" method. Moreover, depending on the size and depth of the data a method can suddenly become faster than an other. And that's not to speak about the query itself. by example $('#id .class') might not use the same "engine" as $('#id').find('.class').

All in all, it's not a problem, jquery is quite optimized. When I stumble upon performance issues, it's quite never due to selectors (but to .append(), big , non delegated events or plugins, and overall: my plain old bad coding).

if you really, really need performance on the dom, you have to compare performance with 'document.getElementbyId' (when you have an id to use it with), and native 'document.querySelectorAll', which seems to be the fastest method of the month.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK