tags:

views:

71

answers:

5

Is there any performance difference between using two separate calls to hide two elements, or would it be more/less efficient to use only 1 statement? Is there any practical difference?

$('#container1').hide();
$('#container2').hide();

vs:

$('#container1, #container2').hide();

Also, which do you think is more readable?

A: 

It doesn't matter from an efficiency standpoint. I think the second option is better for readability, if you don't need to attach separate events to one of the elements: $('#containter1').hide().html('foo'); ...and no the other element.

jeerose
+4  A: 

There is a minor performance difference in that the same delegate is being called on both elements, but this is a very, very minor memory allocation. Any extra lines of code also mean more work for the javascript interpreter and work for the browser...that's more of a difference than anything, but still an infinitesimally small difference.

Short answer: the second one is slightly faster/uses less memory, it's so insanely insignificant you probably couldn't measure without looping tens of thousands of times.

Nick Craver
@Nick - Out of curiosity, will both of these result in two DOM traversals, or will the second version accomplish both in one traversal?
patrick dw
@patrick - Well both have 2 "traversals", but that's not a great term when using the `#ID` selector, in that case you're asking the browser to return the element directly (usually from an internal hash table, which is why it's so fast). You're calling a method, getting an element...so you're not doing any traversing/crawling/searching when using an ID. When using multiple selectors, Sizzle is just taking them and fetching them 1 by 1 adding them to the collection (optimizing where possible, of course) With respect to **fetching the ID element**, both perform the same amount of work.
Nick Craver
@Nick - Thanks so much for the explanation. I always wondered how elements were acquired. I somehow assumed that full DOM traversals were needed for selection. Glad to hear that's not the case. Thanks again!!!
patrick dw
A: 

1st solution is more readable. 2nd solution have similar performance as the first.

uthark
+1  A: 

In this specific case, it would not make a practical difference. You're still looking for two specific id's in the DOM.

As far as readibility goes, I would keep them in one statement, as long as they are logically grouped.

However, if your next line is something that operates on container2 sepearately, then separate the 2. No need to do extra traversals. For example:

//2 dom traversals
$('#container1').hide();
$('#container2').hide().html(some_html);

is faster than

//3 dom traversals
$('#container1, #container2').hide();
$('#container2').html(some_html);
Mike Sherov
A: 

Both are pretty much the same, the second is a few characters shorter if that's a consideration that's important for you.

Naeem Sarfraz