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.