Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

optimization - Most efficient way to find elements in jQuery

If I have a CSS class which I only ever apply to form elements, eg:

<form class="myForm">

Which of these two jQuery selectors is most efficient, and why?

a) $('form.myForm')

b) $('.myForm')
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Edit: The results below are for jQuery 1.2.6, probably in Firefox 3.5. Speed improvements in browsers and jQuery itself have pretty much rendered this information obsolete.


I just wrote a quick benchmarking test:

  • On a page with 4 forms and about 100 other elements:
    • Using $('form.myForm') 10000 times took 1.367s
    • Using $('.myForm') 10000 times took 4.202s (307%)
  • On a page with only 4 forms and no other elements:
    • Using $('form.myForm') 10000 times took 1.352s
    • Using $('.myForm') 10000 times took 1.443s (106%)

It appears that searching for elements of a particular name is much quicker than searching all elements for a particular class.

Edit: Here's my test program: http://jsbin.com/ogece

The program starts with 100 <p> tags and 4 <form>s, runs the two different tests, removes the <p> tags and runs the test again. Strangely, when using this technique, form.myForm is slower. Take a look at the code for yourself and make of it what you will.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...