Search code examples
jqueryperformancecachingjquery-selectorschaining

Cached vs chained selectors in jquery?


I am wondering if there is a performance difference between using a cached selector, and using chained selectors?

If I understand it correctly the chaining works because each function returns the jquery object, which is exactly the same as what is contained in the cached selector. So there would be no difference performance wise in the two examples below is there?


Cached Selector

$(function(){

    $.on('click', '.disabled', function(){
        $toggle = $(this);
        $toggle.attr('title', 'Object Enabled');
        $toggle.toggleClass('disabled enabled');
        $toggle.html('Enabled');
    });
});


Chained Selector

$(function(){

    $.on('click', '.disabled', function(){
        $(this)
            .attr('title', 'Object Enabled')
            .toggleClass('disabled enabled')
            .html('Enabled');
    });
});

Solution

  • You can see here

    http://jsperf.com/jquery-chaining

    That the difference is negligible.

    Chained

    $('#theDiv').addClass('test').removeClass('test');
    
    59,874 Operations / Second
    

    Separate calls (cached)

    var d = $('#theDiv');
    d.addClass('test');
    d.removeClass('test');
    
    62,021 Operations / Second