多选择器与单选择器性能 [英] Multiple selector vs single selector performance

查看:70
本文介绍了多选择器与单选择器性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试找到答案了,我找到了相关的问题,虽然他们确认了我的发现(

我猜第二次操作占用的时间最多。


I've tried finding an answer, and I've found related question, and while they confirm my findings (that one multiple selector call is slower than multiple single selector calls) none of them tell me why.

basically, when you run this code:

$("#one, #two").hide();
$("#one, #two").show();

Against this code:

$("#one").hide();
$("#two").hide();
$("#one").show();
$("#two").show();

Then the latter will be faster by about 50%.

However, once we add a third selector, the performance difference is 39% faster.

Fourth selector difference: 26% faster.

Fifth: 30% faster.

Sixth: 31% faster.

Ten: 31% faster.

(Do note these values seem to range in about a 5% margin)

So we get something that looks like this:

The performance seems to plateau around 6 selectors. It never seems to get any 'faster' than being 31% slower than doing each one through a single call. Why is that?

Personally, I love using multiple selectors per call, but it seems to have a (relatively) large performance hit. When would this (not) be appropriate to use?

解决方案

In both cases you operates on IDs, so it can be converted to native getElementById call.

However, in 1st case 2 additional things must be done

  1. The coma must be processed, so there is additional parsing involved
  2. The 2 results must be merged, by which operation the jQuery asserts that they are returned in the same order as in DOM

I guess the second operation takes the most time.

这篇关于多选择器与单选择器性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆