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?
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With