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')
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')
I just wrote a quick benchmarking test:
$('form.myForm')
10000 times took 1.367s$('.myForm')
10000 times took 4.202s (307%)$('form.myForm')
10000 times took 1.352s$('.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.
The first selector should be faster because jQuery can use the built-in function "getElementsByTagName" to reduce the number of elements it needs to filter. The second one has to get all the elements in the DOM and check their class.
form.myForm IMO is much quicker as it only needs to be look at a subset/filtered set of elements and would not need to iterate the whole document.
Try slickspeed where you can see the rough speeds of selectors across a multiple of js libs including jquery.
The first example goes a LOT faster when used with a context. The second example goes faster as well, but not by much. I expanded your example to compare with a context:
enobrev, Interesting. I just ran your example but using jquery 1.3 beta 2 here
results.... (1.2.6 speed in brackets)
// With 100 non-form elements and Context:
$('.myForm', '#someContainer') : 4063ms (3707ms)
$('form.myForm', '#someContainer') : 6045ms (4644ms)
// With 100 non-form elements:
$('.myForm') : 3954ms (25086ms)
$('form.myForm') : 8802ms (4057ms)
// Without any other elements with Context:
$('.myForm', '#someContainer') : 4137ms (3594ms)
$('form.myForm', '#someContainer') : 6627ms (4341ms)
// Without any other elements:
$('.myForm') : 4278ms (7303ms)
$('form.myForm') : 8353ms (4033ms)