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
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
:checkedselector epxression.In reality, the speed difference between the two is not going to be a showstopper 🙂
I’d be inclined to use
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).