JQuery / JavaScript performance using $ (this)

I find myself doing this with JQuery:

$('.filter-topic-id').each(function () {
    var me = $(this);
    if (me.text() == topics[k]) {
        me.parent().show();
    }
});

      

I am storing $(this)

in a named variable me

because I'm afraid it will over-evaluate $(this)

for no reason. Are the underlying JavaScript engines smart enough to know they don't need to reevaluate it? Maybe even JQuery is smart enough?

+2


source to share


6 answers


They're not smart enough not to repeat the re-evaluation $(this)

if that's what your code says. Caching a jQuery object in a variable is best practice.

If your question is about your way in question versus this way



$('.filter-topic-id').each(function () {
    if ($(this).text() == topics[k]) { // jQuery object created passing in this
        $(this).parent().show(); // another jQuery object created passing in this
    }
});

      

Your path is best practice.

+3


source


Are the main engines of JavaScript smart enough to know they don't need to overestimate it?

Not. But if you are using jQuery, you are probably aiming for readability rather than maximum performance.



Write whichever version you find the easiest to read and maintain, and don't worry about these micro-optimizations until your page is too slow and you've exhausted other more significant sources of latency. There is $(node)

not much work in the call .

+2


source


You can try to profile your code with Firebug and see if using $ (this) will slow down your application multiple times or not

+1


source


There is no good way for javascript to determine that the following is true: -

fn(x) == fn(x);

      

Even if it were possible, calling the second fn

could only be valid if it could be protected, which fn

has no other side effects. When there is other code between calls to fn

, then its even more complicated.

Hence, Javascript engines have no choice but to call fn

on every call.

The overhead of calling $ () is fairly small, but not insignificant. I would of course store the result in a local variable like you do.

+1


source


this is just a reference to the current DOM element on iteration, so there is little or no overhead when calling $ (this). It just creates a jQuery wrapper around the DOM element.

0


source


I think you'll find that calling a jQuery function by passing a dom element is perhaps the least intensive way to construct an object. It shouldn't do any lookups or query the DOM, just wrap it up and return.

That said, it definitely doesn't stop me from using the method you are using there and what I do all the time on my own. This definitely helps when creating nested closures:

$('div').click(function() {
    var $this = $(this);
    $this.find("p").each(function() {
        // here, there no reference to the div other than by using $this
        alert(this.nodeName); // "p"
    });
});

      

0


source







All Articles