1

Possible Duplicate:
What is the cost of '$(this)'?

I constantly see in some developers code where $(this) may exist 3-5 times referring to the same dom node. I'm wondering at what point this is worth optimizing and storing in a variable like var el = $(this); ?

Does anyone know of a good reliable source for documentation on the performance of this?

Community
  • 1
  • 1
Ben
  • 60,438
  • 111
  • 314
  • 488
  • 1
    well the advantages of caching doesn't need support of any documentation IMO... – Rafay May 18 '12 at 18:46
  • tbh, 3-4 times is not going to be a rip off.. coz `this` is available in local scope.. but always better to have cached.. I would cache more complicated selectors and based on their usage.. – Selvakumar Arumugam May 18 '12 at 18:47
  • 3
    Take a look: http://stackoverflow.com/questions/10433014/what-is-the-cost-of-this/ – VisioN May 18 '12 at 18:48
  • I bet if you ran a test comparison running 1000 iterations on the same function, there'd be less than 10 ms of difference. So if you're doing one iteration at a time... In practice it'll be around the same, it's only a matter of theory and coding style IMO. – frenchie May 18 '12 at 18:48

4 Answers4

5

If you have to use it more than once, cache it. IMHO, why keep calling the DOM for something?

Note: I recommend adding a $ before the variables that are actually jquery DOM elements. It makes it easier to keep track of what the variable really is.

Josh Mein
  • 28,107
  • 15
  • 76
  • 87
5

I use var $this = $(this);

This article provides performance analysis. You'll save 1 second after 10,000 calls :) http://www.stoimen.com/blog/2010/06/19/speed-up-the-jquery-code-selectors-cache/

Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
2

If you cache it in a variable it is also less to type but can also be optimized by minifiers since $(this) cannot be minified while a local variable referring to $(this) will probably be minified to one character

Esailija
  • 138,174
  • 23
  • 272
  • 326
-2

this means the element it just tagger an event.

$("input").click(function(){
  $(this)// this refer to the input element that you click
})

when we need to store this element, we use a variable to store it. so the el of var el = $(this) also means the input element.

panda
  • 1,344
  • 3
  • 14
  • 35