views:

52

answers:

3

I have the following two code blocks.

Code block 1

var checkboxes = $("div.c1 > input:checkbox.c2", "#main");
var totalCheckboxes = checkboxes.length;
var checkedCheckboxes = checkboxes.filter(":checked").length;

Code block 2

var totalCheckBoxes = $("div.c1 > input:checkbox.c2", "#main").length;
var checkedCheckBoxes = $("div.c1 > input:checkbox.c2:checked", "#main").length;

Which one of the above will be faster?

Thanks,

Rahul

+2  A: 

Number 1 will be slightly faster as the filter is applied to an object containing the selected elements already. Number 2 basically performs the same selector query twice, the second time including the :checked selector epxression.

In reality, the speed difference between the two is not going to be a showstopper :)

I'd be inclined to use

var checkboxes = $("#main").find("div.c1 > input:checkbox.c2");
var totalCheckboxes = checkboxes.length;
var checkedCheckboxes = checkboxes.filter(":checked").length;

Supplying the context will make essentially resolve to the above, but using .find() has been shown to be faster (I'll dig out the reference, I believe it was on John Resig's blog).

Russ Cam
But this action is a bit slower in IE compared to Chrome or FF.
rahul
My question is then, what is the main browser for your target audience? Use the method that will provide the best performance in the majority of cases? How did you measure the performance in each browser, and in what version(s) of IE?
Russ Cam
The site has to run on IE6+, FF and Chrome. I have tested it in IE6, 7 and 8.
rahul
*Everything* is going to be slow on IE6... :)
Aistina
+1  A: 

Maybe write a small test and benchmark it using different browsers.

Anthony
A: 

If you want performance, don't be that specific if you can avoid it.

For instance, if you can afford just to lookup class 'c2' it should improve the selecter speed.

$("#main").find(".c2")

should be the fastest solution.

Kind Regards

--Andy

jAndy