在jQuery中,按类或id选择比通过其他属性选择更快?

时间:2021-06-11 15:41:31

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选择最快,然后是类,然后是属性),但有人知道吗?

6 个解决方案

#1


70  

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应该是唯一的,因此API在DOM中找到ID后停止搜索。

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

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

For example...

例如...

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

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

somecontainer就像div一样,围绕一个带有someclass类的元素。在某些容器包含一小部分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.

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

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

以下是10,000次迭代的结果(代码如下):

IE9

IE9

$(".someclass") - 2793 ms

$(“。someclass”) - 2793 ms

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

$(“。someclass”,“#somecontainer”) - 1481 ms

Chrome 12

Chrome 12

$(".someclass") - 75 ms

$(“。someclass”) - 75毫秒

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

$(“。someclass”,“#somecontainer”) - 104毫秒

Firefox 3.6

Firefox 3.6

$(".someclass") - 308 ms

$(“。someclass”) - 308毫秒

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

$(“。someclass”,“#somecontainer”) - 357 ms

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有所帮助。较旧的浏览器也将受益于context参数。但考虑到这些浏览器的流行并将所有内容平均化,现在净收益有点大。

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>

#2


11  

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")

#3


7  

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

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

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

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

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

$(。unique_class')=> 45,257 ops / sec,慢40%:页面上只有一个类

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

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

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

$(“。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

#4


7  

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实现的不同,性能会因浏览器(版本)和浏览器(版本)而异。至少,这就是我相信事物的方式。

#5


2  

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”类元素的父元素具有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.

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

#6


0  

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

#1


70  

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应该是唯一的,因此API在DOM中找到ID后停止搜索。

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

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

For example...

例如...

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

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

somecontainer就像div一样,围绕一个带有someclass类的元素。在某些容器包含一小部分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.

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

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

以下是10,000次迭代的结果(代码如下):

IE9

IE9

$(".someclass") - 2793 ms

$(“。someclass”) - 2793 ms

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

$(“。someclass”,“#somecontainer”) - 1481 ms

Chrome 12

Chrome 12

$(".someclass") - 75 ms

$(“。someclass”) - 75毫秒

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

$(“。someclass”,“#somecontainer”) - 104毫秒

Firefox 3.6

Firefox 3.6

$(".someclass") - 308 ms

$(“。someclass”) - 308毫秒

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

$(“。someclass”,“#somecontainer”) - 357 ms

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有所帮助。较旧的浏览器也将受益于context参数。但考虑到这些浏览器的流行并将所有内容平均化,现在净收益有点大。

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>

#2


11  

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")

#3


7  

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

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

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

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

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

$(。unique_class')=> 45,257 ops / sec,慢40%:页面上只有一个类

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

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

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

$(“。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

#4


7  

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实现的不同,性能会因浏览器(版本)和浏览器(版本)而异。至少,这就是我相信事物的方式。

#5


2  

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”类元素的父元素具有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.

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

#6


0  

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