2

I understand that referencing $('#Counter') over and over is a bad idea because you are "jumping into the DOM each time".

But is this any better?

Counter = $('#Counter');

And then inside the loop:

Counter.val()++

Edit:

Correction to the snippet above, which should be:

Counter.val(Counter.val()+1);

Or is that doing the same thing?

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • 2
    Yes, it is better. You're querying the DOM once vs. *N* times. – Andrew Whitaker Mar 25 '13 at 19:44
  • It's a bit more efficient to use a variable if you plan on re-using it more than once. jQuery will cache selectors and results, by using the variable you bypass the need for that extra code. – Louis Ricci Mar 25 '13 at 19:45
  • Yeah, but the variable is just pointing to the DOM. – Phillip Senn Mar 25 '13 at 19:45
  • 8
    That looks like a good improvment and an example of how to cache and element from the DOM... Throw a `var` in front of `Counter` and we'll give you a gold star. – jahroy Mar 25 '13 at 19:45
  • `Counter.val()++` will be a runtime error - you can't assign to the result of calling this function. Did you want `Counter.val()+1`? – Bergi Mar 25 '13 at 19:46
  • done. However, I'm thinking of putting any "DOM cache" variables into the global scope. – Phillip Senn Mar 25 '13 at 19:46
  • @Bergi Thanks for catching that. – Phillip Senn Mar 25 '13 at 19:48
  • Ok... If that's what you **really** want to do, no need for var. Maybe you should cache your DOM elements inside of a single object that is global (rather than polluting the global scope)? As that owl used to say: "_Give a hoot, don't pollute!_" ;-) – jahroy Mar 25 '13 at 19:48
  • possibly related to [jquery .val() += idiom](http://stackoverflow.com/questions/10487850/jquery-val-idiom) – Bergi Mar 25 '13 at 19:48
  • @Bergi I don't think that's the point at all. The OP was just demonstrating what they were doing inside the loop. This is no duplicate. The question's about caching, not specifically what for. Your suggestion was clearly correct – Ian Mar 25 '13 at 19:50

1 Answers1

6

For the case you described, it is preferrable to save jQuery object in a variable before entering the iteration statement, where you repeatedly use this object. It will prevent of traversing the DOM tree at each iteration. Besides it can be insensible for searching by ID, but querying by class name or using compound selectors may sufficiently decrease the performance.

var $Counter = $("#Counter");
for (...) {
    $Counter.val(function(i, val) { return +val + 1; });
    ...
}

Pay attention to using function as argument of val() which is more reasonable in this case.

VisioN
  • 143,310
  • 32
  • 282
  • 281