Why is jQuery selector function so slow compared to native DOM methods

Alexander picture Alexander · Dec 7, 2013 · Viewed 9.8k times · Source

I know this topic has been debated in general several times already, but I am looking for a more technical and detailed insight to understand what is really going on.

I devised a series of tests to compare speed of jQuery's most basic selectors '#id' and '.class' to various native DOM methods.

What I wish is to find out exactly why the results are what they are.

Here are the tests : http://jsperf.com/jqueryspeed

The main thing noticeable, is that getElementById is clearely the fastest of all. To compare, I added both jQuery('#id') and jQuery.fn.init('#id') as tests, the difference between the two is that the first one does instanciate a whole new jQuery object, while the second one only runs the prototype function, and is thus faster. So, the difference between those two is understandable.

The main difference that I do NOT understand however, is the huge gap between the speed of getElementById and the speed of jQuery.fn.init, which has a simple test to handle a simple ('#id') request in a specific way, falling back to a call to getElementById itself.

So, why for example on Chrome, is this method about 8 times slower than the native one, even though it basicly is just a wrapper for it ?

It is also about 3-4 times slower than the wrapped getElementById $(document.getElementById('#id'))...

Any ideas please ?

Answer

HIRA THAKUR picture HIRA THAKUR · Dec 7, 2013

This is the amount of code jquery goes through when we use a simple $('selector')

http://james.padolsey.com/jquery/#v=1.10.2&fn=init

As you can see,there are plenty of validation done,regex matches,cross browser tricks etc.

Its important to realise that jquery is a library built on javascript.Javascript executes directly on the browser.Where as jquery processes quite a lot of javascript code before being executed by the browser.

I personally prefer jquery.I am really not bothered about saving those nano seconds.The level of simplicity that jquery provides is phenomenal and an artpiece in itself.