Skip to content Skip to sidebar Skip to footer

Is Id Selector Faster Than Class Selector When It Is Cached In Jquery

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 selector, or

Solution 1:

The cached reference to a DOM node is always the fastest possible way. So once you have a reference stored, it makes no difference how it did get there.

The bridge example

Imagine there is a bridge between your Javascript world and the DOM world. Each time you want to access an element (a "citizen") from Javascript in the DOM world, you need to cross that bridge.. but that is not for free.. you need to pay a pretty expensive toll. So you should only go that way once and therefore only pay once.

If you know the exact position of the element (which is stored in a variable) you can just access it in no time.

Solution 2:

You have those stored in variables. So the speed will be the same for both.

The performance hit will occur when you are iterating DOM to get elements. At that time ID selector will be faster than class selector.

Solution 3:

Just to make sure I'm not missing the mark... I think you mean

<divclass="myclass"></div><divid="myid"></div>

and then in jquery your doing:

var $myclass = $('.myclass');
var $myid = $('#myid');

My understanding of jquery is that when creating the vars creating the $myclass is not as fast as creating the $myid... but when you go back to use them later. they will be the same speed.

Solution 4:

As you said, the ID is the faster lookup, but which one you chose has more to do with what you want to do.

Think of a class like a category, or classification for different items that have a common or shared aspect to them, while an ID in contrast, has some unique property it is one of a kind. If we were dealing with monetary values, there are many individual figures, and some subtotals and but only one total. You may want to use a .figure class to format the styling of all the individual figures, a .subtotal class for each subtotal so you could style them differently, and you could assign an id to the total, because you want it to have unique styling, and there will only be one.

If you dynamically wanted to find all the values and convert them to a different currency, it would be a simple thing to find all the values and writing the code to convert them all at once would be trivial, while writing the code to find each number by id would be tedious at best and confusing.

So, it really depends on what you are trying to do. If you want to find one and only one item, an id is far faster, but if all the items have something in common, it is certainly simpler (and possibly faster) to reference them all by class instead. I would be curious to see a test result comparing those ...

Code to update all the values on click of a convert button after someone enters a conversion ratio:

$('#convertBtn').on('click', function () {
    var factor = $('#convRatio').val();
    var$err = $('#errorPanel');// only create once to save resources if (factor) {
        // remove any error conditionif ($err.text()) {
            $err.text("");
        }
        // get an array-like object of all the valuesvar$vals = $('#total, .subtotal, .figures');

        $vals.each(function () {
            var$th = $(this);// only create once to save resourcesvar val = $th.text();

            $th.text(val * factor);
        });
    } else {
        $err.text("Please enter a conversion rate");
    }
});

Code to highlight just the subtotals when you click on one of them:

var$subs = $('.subtotals');

$subs.on('click', function () {
    var$sub = $(this);// only create once to save resourcesif ($sub.hasClass('hilite')) {
        $sub.addClass('hilite');
    } else {
        $sub.removeClass('hilite');
    }
}

Code to highlight just the total when clicked:

var$tot = $('#total');// only create once to save resources// toggle highlighting on and off when any subtitle is clicked$tot.on('click', function () {
    if ($tot.hasClass('hilite')) {
        $tot.addClass('hilite');
    } else {
        $tot.removeClass('hilite');
    }
}

Solution 5:

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 listvar myList = $('.myList');
var myListItems = '<ul>';

for (i = 0; i < 1000; i++) {
    myListItems += '<li class="listItem' + i + '">This is a list item</li>';
}

myListItems += '</ul>';
myList.html(myListItems);

// Select each item oncefor (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 listvar myList = $('.myList');
var myListItems = '<ul>';

for (i = 0; i < 1000; i++) {
    myListItems += '<li id="listItem' + i + '">This is a list item</li>';
}

myListItems += '</ul>';
myList.html(myListItems);

// Select each item oncefor (i = 0; i < 1000; i++) {
    var selectedItem = $('#listItem' + i);
}

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

Post a Comment for "Is Id Selector Faster Than Class Selector When It Is Cached In Jquery"