views:

49

answers:

4

To put it simply:

Is this:

var x = $('#selector-id');
x.slideDown();

Faster than:

var x = $('#selector-id');
$(x).slideDown();
+2  A: 

The second example doesn't make sense, as x is already a jQuery object.

It would make more sense if you did:

var selector_string = '#selector-id';
$(selector_string).slideDown();

but that would definitely be slower than the first option as you'll be accessing the DOM and making a new jQuery object every time you use it.

Skilldrick
I wouldn't call `getElementById()` "traversing the DOM", but yes it is wasteful :)
Nick Craver
That's true, but I've seen people do the second one a lot so I was just wondering. I thought the first one was more efficient too, thanks for the replies!
Nico Hämäläinen
@Nick - in that case I guess not, but I'm thinking of the more general case of `var x = someKindOfSelectorAsAString;`
Skilldrick
@Nick: better? :)
Skilldrick
@Skilldrick - much, thanks! :)
Nick Craver
A: 

Theoretically it is faster because it makes one less function call. Practically you would never write the second because x is already a jQuery object.

Darin Dimitrov
+2  A: 

The second version clones the jQuery object...for no reason really, so yes the first is both faster and more efficient (less wasteful).

Nick Craver
A: 

remember dom acessing just slowdowns your javascript, more you access the DOM more less efficient it becomes.

below are few examples

var _elm= jQuery('.myElement');
_elm.DoThis();
_elm.DoThat();

above 2 will be faster than below written 2

jQuery('.myElement').DoThis();
jQuery('.myElement').DoThat();

// you may use firebug's profiler to test this.

Praveen Prasad