Is ID selector faster than class selector when it is cached in jquery

后端 未结 5 1328
长发绾君心
长发绾君心 2020-12-21 05:01

I know that ID is a faster selector than class in Javascript. But what if I cache the selector? When the selector is cached, would it differ in speed if it’s a class selecto

5条回答
  •  自闭症患者
    2020-12-21 05:57

    Have a look at this tips

    http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx?sms_ss=favorites

    Above link suggest to Use IDs instead of classes wherever possible

    Description here:

    jQuery makes selecting DOM elements using classes as easy as selecting elements by ID used to be, so it's tempting to use classes much more liberally than before. It's still much better to select by ID though because jQuery uses the browser's native method (getElementByID) to do this and doesn't have to do any of it's own DOM traversal, which is much faster. How much faster? Let's find out.

    I'll use the previous example and adapt it so each LI we create has a unique class added to it. Then I'll loop through and select each one once.

    // Create our list
    var myList = $('.myList');
    var myListItems = '
      '; for (i = 0; i < 1000; i++) { myListItems += '
    • This is a list item
    • '; } myListItems += '
    '; myList.html(myListItems); // Select each item once for (i = 0; i < 1000; i++) { var selectedItem = $('.listItem' + i); }

    Just as I thought my browser had hung, it finished, in 5066 milliseconds (over 5 seconds). So i modified the code to give each item an ID instead of a class and then selected them using the ID.

    // Create our list
    var myList = $('.myList');
    var myListItems = '
      '; for (i = 0; i < 1000; i++) { myListItems += '
    • This is a list item
    • '; } myListItems += '
    '; myList.html(myListItems); // Select each item once for (i = 0; i < 1000; i++) { var selectedItem = $('#listItem' + i); }

    This time it only took 61 milliseconds. Nearly 100x faster.

提交回复
热议问题