Javascript 在 jQuery 中,按类或 id 选择是否比按其他属性选择更快?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6460644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:51:31  来源:igfitidea点击:

In jQuery, is selecting by class or id faster than selecting by some other attribute?

javascriptjqueryjquery-selectors

提问by Jay

Basically, is

基本上,是

$("#someid")

or

或者

$(".someclass")

faster than

比...快

$("[someattr='value']")

I would imagine that it is (that is, selection by id is fastest, then class, then attribute), but does anyone know for sure?

我会想象它是(也就是说,通过 id 选择最快,然后是类,然后是属性),但是有人确定吗?

回答by Steve Wortham

ID is absolutely the fastest. Part of the reason is that ID is supposed to be unique, so the API stops searching after the ID is found in the DOM.

ID绝对是最快的。部分原因是 ID 应该是唯一的,因此在 DOM 中找到 ID 后,API 停止搜索。

If you must use a class or attribute selector, you can improve performance by specifying the optional context parameter.

如果必须使用类或属性选择器,则可以通过指定可选的上下文参数来提高性能。

For example...

例如...

$(".someclass", "#somecontainer")

Where somecontaineris something like a div, surrounding an element with class someclass. This can offer a huge performance benefit in the cases where somecontainercomprises a small fraction of the DOM.

somecontainer像 div 一样的东西在哪里,用 class 围绕一个元素someclass。在somecontainer包含一小部分 DOM的情况下,这可以提供巨大的性能优势。



UPDATE:

更新:

I did some tests a couple years ago around the context parameter. After reading the comments below I was curious if anything has changed. Indeed, it seems the scene has changed somewhat with today's browsers. Maybe it also has to do with improvements in jQuery? I don't know.

几年前我围绕上下文参数做了一些测试。阅读下面的评论后,我很好奇是否有任何变化。事实上,现在的浏览器似乎已经改变了这一场景。也许它也与 jQuery 的改进有关?我不知道。

Here are my results with 10,000 iterations (code is below):

这是我经过 10,000 次迭代后的结果(代码如下):

IE9

IE9

$(".someclass")- 2793 ms

$(".someclass")- 2793 毫秒

$(".someclass", "#somecontainer")- 1481 ms

$(".someclass", "#somecontainer")- 1481 毫秒

Chrome 12

铬 12

$(".someclass")- 75 ms

$(".someclass")- 75 毫秒

$(".someclass", "#somecontainer")- 104 ms

$(".someclass", "#somecontainer")- 104 毫秒

Firefox 3.6

火狐 3.6

$(".someclass")- 308 ms

$(".someclass")- 308 毫秒

$(".someclass", "#somecontainer")- 357 ms

$(".someclass", "#somecontainer")- 357 毫秒

So among these big 3 modern browsers, the context parameter only seems to help IE9. Older browsers will also benefit from the context parameter. But considering the prevalence of each of these browsers and averaging everything out, the net gain is somewhat of a wash now.

所以在这三大现代浏览器中,context 参数似乎只对 IE9 有帮助。较旧的浏览器也将从上下文参数中受益。但考虑到这些浏览器中的每一种的流行程度和平均所有内容,净收益现在有点小了。

And here's the code in case anyone wants to try it themselves...

这是代码,以防有人想自己尝试...

<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){

                startTime = new Date().getTime();               
                for (i = 0; i < 10000; i++)
                {
                    s = $(".someclass");
                }           
                $("#withoutcontext").html(elapsedMilliseconds(startTime));


                startTime = new Date().getTime();
                for (i = 0; i < 10000; i++)
                {
                    s = $(".someclass", "#somecontainer");
                }           
                $("#withcontext").html(elapsedMilliseconds(startTime));

            });

            function elapsedMilliseconds(startTime)
            {
                var n = new Date();
                var s = n.getTime();
                var diff = s - startTime;
                return diff;
            }
        </script>
    </head>
    <body>
        <h1>jQuery Selector Performance: Context vs No Context</h1>

        <h2>$(".someclass")</h2>
        <span id="withoutcontext">---</span> ms<br /><br />

        <h2>$(".someclass", "#somecontainer")</h2>
        <span id="withcontext">---</span> ms<br /><br />

        <hr />

        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <div id="somecontainer">
            <p class="a">a</p>
            <p class="b">b</p>
            <p class="c">c</p>
            <p class="someclass">someclass</p>
        </div>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
        <p class="a">a</p>
        <p class="b">b</p>
        <p class="c">c</p>
    </body>
</html>

回答by a programmer

Selecting by ID is the fastest, because it maps directly to getElementByID, the other 2 has to check each element to determine the selected elements.

按ID选择是最快的,因为它直接映射到getElementByID,另外2个要检查每个元素来确定被选中的元素。

If you must select using class or attribute, then try enclosing the search in a ID. ex.

如果您必须选择使用类或属性,请尝试将搜索包含在 ID 中。前任。

$("#someid .someclass")

回答by ewwink

ID is unique and if you only want to select one/first element here the equivalent

ID 是唯一的,如果您只想在此处选择一个/第一个元素,则等效

$("#someid") => 75,695 ops/sec, fastest

$(.unique_class') => 45,257 ops/sec, 40% slower : only one class on page

$(".someclass").first() => 42,217 ops/sec, 46% slower : multiple class on page, select first element

$(".someclass:eq(0)") => 18,324 ops/sec, 76% slower : multiple class on page, select element at selected index

$("#someid") => 75,695 ops/sec,最快

$(.unique_class') => 45,257 次操作/秒,慢 40%:页面上只有一个类

$(".someclass").first() => 42,217 ops/sec,慢 46%:页面上有多个类,选择第一个元素

$(".someclass:eq(0)") => 18,324 ops/sec,慢 76%:页面上有多个类,选择选定索引处的元素

Test url: http://jsperf.com/jquery-selector-speed-tests/98

测试网址:http: //jsperf.com/jquery-selector-speed-tests/98

回答by BoltClock

ID and class selectors, at least when used by themselves, tend to be faster, whether for jQuery or for CSS. This is due largely to the fact that browsers have optimized algorithms for IDs and classes in their DOM/CSS engines.

ID 和类选择器,至少在单独使用时,往往更快,无论是对于 jQuery 还是 CSS。这主要是因为浏览器在其 DOM/CSS 引擎中针对 ID 和类优化了算法。

In modern browsers with recent versions of jQuery, any selector strings that are understood as supported CSS selectors by a browser will be handled by document.querySelectorAll(), offering maximum performance as long as standard CSS selectors are used. Non-standard selectors or older browsers are taken care of by jQuery and/or the Sizzle library, which do their best to make use of the DOM's get-element(s) methods to traverse the DOM.

在具有最新 jQuery 版本的现代浏览器中,任何被浏览器理解为支持的 CSS 选择器的选择器字符串都将由 处理document.querySelectorAll(),只要使用标准 CSS 选择器就可以提供最佳性能。非标准选择器或旧浏览器由 jQuery 和/或 Sizzle 库处理,它们尽最大努力利用 DOM 的 get-element(s) 方法来遍历 DOM。

The most important thing to remember is that performance will vary from browser (version) to browser (version) because of differing DOM implementations. At least, that's how I believe things are.

要记住的最重要的事情是,由于 DOM 实现不同,性能会因浏览器(版本)而异。至少,我相信事情是这样的。

回答by Mark Schultheiss

The id will always be fastest as it it unique on the page. The class "may" be faster than an attribute but it depends.

id 总是最快的,因为它在页面上是唯一的。类“可能”比属性更快,但这取决于。

The real kicker here is selection of a class within and ID may NOT be faster than just selection of the class. It will depend on the page and browser. In my testing, selection of a complex page with a limited number of elements with a "class" where the parent of the class element had an id such as:

这里真正的关键是选择一个班级,ID 可能不会比选择班级更快。这将取决于页面和浏览器。在我的测试中,选择了一个包含有限数量元素的复杂页面,其中包含一个“class”,其中 class 元素的父元素具有一个 id,例如:

<div id='iamout'>
  <div class='aonther'>
    <div class='iamin'>stuff</div>
    <div class='iamin'>stuff</div>
  </div>
</div>

a selector such as $('.iamin','#iamout')was not always as fast as $('.iamin')

像这样的选择器$('.iamin','#iamout')并不总是那么快$('.iamin')

Not all browsers support select by classname (natively), but modern/newer ones do and thus it might offer better performance depending upon which browser you have.

并非所有浏览器都支持按类名(本机)选择,但现代/较新的浏览器支持,因此它可能会根据您拥有的浏览器提供更好的性能。

If you need to have optimum performance you will need to test your exact page.

如果您需要获得最佳性能,则需要测试您的确切页面。

回答by webtrifusion

Id is fastest, because it is the only element that can have that identifier. Many objects could possibly have the same class name. Someone could verify this, but it would seem like the document would not need to be traversed any further once the id was found. For classes this may not be the case?? HTH

Id 是最快的,因为它是唯一可以具有该标识符的元素。许多对象可能具有相同的类名。有人可以验证这一点,但似乎一旦找到 id 就不需要进一步遍历文档了。对于课程,情况可能并非如此??HTH