wsanville
wsanville

Reputation: 37516

jQuery selector performance - One statement vs two

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?

Upvotes: 6

Views: 269

Answers (4)

Naeem Sarfraz
Naeem Sarfraz

Reputation: 7430

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

Upvotes: 0

Mike Sherov
Mike Sherov

Reputation: 13427

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);

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630379

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.

Upvotes: 5

jay
jay

Reputation: 10325

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.

Upvotes: 0

Related Questions