0

I have a strange question about jquery selector behavior.

First approach:

$('#div').find('#something').html('hahah');
$('#div').find('#something').html('hahah');
$('#div').show();

Second approach:

var $div = $('#div');
$div.find('#something').html('hahah');
$div.find('#something').html('hahah');
$div.show();

I know that it might not have too much difference, but is the second faster than the first?? I've always used the second approach but I'm not sure if there is a difference because I don't know how the jquery selector algorithm works.

Fabio
  • 11,892
  • 1
  • 25
  • 41

1 Answers1

5

The second way is faster/better because you have cached the selector.

Everytime you call $('selector'), the jQuery selector engine(sizzle) is called to locate your desired elements.

However, when you store them in a variable, you do not need to repeatedly call the selector engine as the results are stored.

Note, in your example above, caching can be further improved by storing the find() result as well

var $something = $('#div').find('#something');
$something.html('hahah');
$something.html('hahah');
$something.show();
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • Thank you man! it works as I thought, but I was not sure... PS: make your post as answer is not available. – Fabio Jun 23 '15 at 20:08