Most efficient way to find elements in jQuery

后端 未结 8 1544
执念已碎
执念已碎 2020-12-16 18:19

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

Which of these two jQuery select

8条回答
  •  轮回少年
    2020-12-16 18:38

    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

    tags and 4 s, runs the two different tests, removes the

    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.

提交回复
热议问题