开发者

jQuery selector performance

I have the following two code blocks.

Code block 1

var checkboxes = $("div.c1 > input:checkbox.c2", "#main");
var totalCheckboxes = checkboxes.length;
var ch开发者_开发问答eckedCheckboxes = 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 :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).


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜