Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does replacing $(this) with a variable make any performance difference [closed]

I have a loop that looks like this:

$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {

    $(this).some code here;
    $(this).some other code there;
    $(this).some other code here and there;
});

If I write at the top of the loop var TheThis = $(this); and then replace $(this) with TheThis is that a performance optimization or not really?

like image 486
frenchie Avatar asked Jan 29 '13 20:01

frenchie


1 Answers

It's a definite performance optimisation. One you'll probably not notice, but that's no reason not to do it.

The code in your example means that the DOM will be interrogated 3 times to look for the $(this) element and then perform the actions on it. Caching it in a variable means that that will only occur once.

If you really want to see the difference try comparing your original with the below in a JSPerf test.

$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {
    var $this = $(this);
    $this.some code here;
    $this.some other code there;
    $this.some other code here and there;
});
like image 62
Rory McCrossan Avatar answered Sep 30 '22 17:09

Rory McCrossan