4

I had code where I add some height to a div:

$('#some_id').height($('#some_id').height() + 100);

I was criticized for this by an employer, who said I shouldn't be using the selector twice. I should cache the first time by doing something like:

 var el = $('#some_id');
 el.height(el.height() + 100); 

I assumed there would only be a tiny saving if I cached elements selected using id, so I never bothered. Am I right?

ebo
  • 2,717
  • 1
  • 27
  • 22
Mark
  • 4,428
  • 14
  • 60
  • 116
  • jQuery cannot watch the DOM for all the changes that may have occurred. It has no choice but to fully reevaluate each selector, every time you use it. Only you can know how the DOM has changed since the last time you used a selector, and whether or not it's appropriate to cache the selected element. – user229044 Jul 01 '14 at 17:21
  • You could argue that caching is a premature optimization. But it is difficult to argue with a person who found dom selections to be the bottleneck in one project and now uses caching everywhere as a good practice. – Pramod Jul 01 '14 at 17:22
  • 3
    The only problem here is that the code is just more messy doing the selector twice. Being concerned with time savings from this tiny operation is just being pretentious. – Mike Jul 01 '14 at 17:22
  • Just FYI for your specific example, you can provide a callback to `.height()` which will "solve" your problem here: http://api.jquery.com/height/#height-function - you could just use `$("#some_id").height(function (idx, height) { return height + 100; });` – Ian Jul 01 '14 at 17:29

0 Answers0