I’m writing some tests for a CMS, and I need to know if a certain classname is in the document.
So I went to investigate what is the fastest way to check if a classname exists in the document. You can see my benchmarks here: http://jsperf.com/if-class-exists
If you run the test, you’ll see ‘getElementsByClassName’ is by far the fastest(99%). This made me wonder if jQuery even checks if there is a native class selector available.
This leaves me wondering what is the best approach, as it is crucial for me to test classnames really fast.
I think you’ve already answered your own question with the jsperf. If speed is really important to you in a particular operation and this test is a valid measure of what you need, then do your own test for
getElementsByClassNameand use it if available as it shows 400x faster in your jsperf.jQuery calls have a reasonable amount of setup overhead that you cans see if you ever step through one. I could imagine in a small document that this setup overhead might skew your jsperf results in a way that wouldn’t be seen as much in a document with a much larger DOM – so I’d suggest you verify your results with a much larger DOM that might be more typical of the documents you will be calling this on.
According to this doc, jQuery should be using
getElementsByClassNamefor a simple class selector.Edit: I stepped through this function call in jQuery
$('.select'). It is using getElementsByClassName internally, but there is a LOT of overhead before it gets there (including even running a complicated regular expression) because of jQuery’s incredible general nature (it has to test a lot of things before it figures out that what you want is a simple class name selector).I thought that if you add a big DOM to your jsPerf, the performance gap might narrow because the jQuery setup overhead will be a much smaller part of the overall execution time, but I didn’t see much change. The
getElementsByClassName('.selector')called all by itself is just way faster thanjQuery('.selector').