Does $ (this) variable replace any difference in performance

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 this performance optimization or not really?

+5
source share
5 answers

This is a definite performance optimization. One of them will probably not notice, but there is no reason not to.

The code in your example means that the DOM will be polled 3 times to find the item $(this), and then perform actions on it. Caching in a variable means that this happens only once.

, JSPerf.

$('#SomeSelectorID').find('.SomeElementsByClassName').each(function () {
    var $this = $(this);
    $this.some code here;
    $this.some other code there;
    $this.some other code here and there;
});
+5

. , $(this) , .

JSFiddle demo .

, . , - . , , , .

...

Testing jquery version...
1000000 iterations $(this): 0.006849ms
Testing non-jquery version...
1000000 iterations of this$: 0.001356ms
+3

, . , . DOM, . jQuery, .

, , , , , , .

+2

, Chrome:

var start = new Date().getTime(),
    iterations = 50000;

$('#foo').find('.bar').each(function () {

    var that = $(this);

    for(var i = 0; i < iterations; i++)
      that.find('i');

});

console.log(new Date().getTime() - start);

$(this) .

http://jsfiddle.net/BuREW/

+1

, .

- . $() ( Vanilla JS) , .

, "".

For example, let's say you want to change all the elements .testto green and delete the class. You can do it:

$(".test").removeClass("test");
$(".test").css({"color":"green"});

Just to find that it does not change color to green, because it is $(".test")no longer the same.

And vice versa, if you did this:

var test = $(".test");
test.removeClass("test");
test.css({"color":"green"});

It works. Of course, this is a trivial example, since you can just rearrange the lines of code, and it works too, but I try to do it here: p

0
source

All Articles