Does jQuery $(this) need to be cached

后端 未结 6 635
一生所求
一生所求 2021-01-13 14:05

I recently came accross some blog posts about jQuery performance (i.e. http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performanc

6条回答
  •  天涯浪人
    2021-01-13 14:53

    Caching this is always a good idea when accessing it multiple times. A thing to note about performance is that this is a JavaScript object--I've seen a lot of code which wraps a jQuery object around this for no reason at all.

    Consider this snippet of code:

    ... (function ()
    {
        alert($(this).attr("class"));
    });
    

    Versus the much cleaner and a bit faster:

    ... (function ()
    {
        alert(this.className);
    });
    


    Update

    In response to your update.. doing:

    ... (function ()
    {
        var that = $(this);
        that.functionCall();
    });
    

    Does not increase performance. It's actually a tiny bit slower, since you are creating a variable on top of wrapping this in a jQuery object.

    If you were to operate on that - the cached $(this) jQuery object - multiple times, you will see an increase performance.. depending on the number of operations:

    ... (function () // calling a function 1000 times on a cached jQuery object
    {
        var that = $(this);
    
        for (var i = 0; i <= 1000; i++)
        {
            /* using a cache will greatly increase performance when
               doing 1000 operations. */
            that.functionCall(); 
        }
    });
    


    On a side-note: if you are interested in jQuery performance optimization, there's a lot of great tips in the jQuery Tips and Tricks question. Give it a go :)

提交回复
热议问题