Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector performance - One statement vs two

Tags:

jquery

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?

like image 390
wsanville Avatar asked Feb 06 '10 13:02

wsanville


2 Answers

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.

like image 122
Nick Craver Avatar answered Nov 02 '22 11:11

Nick Craver


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);
like image 1
Mike Sherov Avatar answered Nov 02 '22 13:11

Mike Sherov