Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

Performance of jQuery selector with context

I was reading this article by Brandon Aaron here, about how jquery context may help. So i thought of doing a test of my own. So this is what I did.

  1. Created a DIV with id="context" and nested DIV with id="holder" in "#context" created earlier.

  2. Created a nested DIVs of depth 18 and append <div id="context"><div id="holder"></div></div> to it resulting in 20 nested DIVs

  3. Now I tested time taken to access "#holder" via the following selectors:
    a. $("#holder") // no context
    b. $("#holder", "#context") // with "#context" selector string
    c. $("#holder", $("#context")) // sending jquery object each time with selector "#context"
    d. $("#holder", $context) // where, var $context = $("#context"). Caching jquery obj
    Each of the cases where accessed X = 1000 times and start and end time difference was noted. I found that time taken for:
    case(a) was the least consistent 28-32msec [jquery-1.3.2]
    case(b)+(c) had the highest times 60-65 msec & 70-75 msec respectively
    case(d) had 40-50msec with 1 or 2 spiked values.

Is this type of basic check valid? You can play with the JS code here at JSBIN. [Do let me know If I can improve this test some how]
If YES, then how does this 'context' really help?


#NOTE: also replace the jquery-1.3.2 with jquery-1.4.2 in jsbin edit mode and you'll be surprised to see the numbers bump up :P

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Context really helps when you have a much larger DOM that you are searching through. Searching for IDs is already very fast and context doesn't really help that much in that case. Where context can really make a difference is when you are selecting by tag name or class.

Try testing like this: http://jsbin.com/aciji4/4

you can really see the timing get better for context when you bump up number of items in the DOM like this: http://jsbin.com/aciji4/6


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...