(Why) Is it faster to use a jQuery-like selector & execute one of its methods, rather than look up a named function?

StackOverflow https://stackoverflow.com/questions/23611492

Question

I was wondering if defining some 'shorthand' functions in your own native JS code is faster than using jQuery (or any other library which returns an object). For example, suppose I would want to add a class to an element.

In jQuery I would do:

$('#sammpleDiv').addClass('someClass');

And in native JS I could do:

// for simplicity's sake, the toElem parameter can only be an id
function addClass(toElem, classToAdd) {
  document.getElementById(toElem).className += ' ' + classToAdd;
};
addClass('sampleDiv','someClass');

EDIT: These are the correct jsPerfs with simple replace & with classList that answer this question

What's faster? According to a jsPerf I made, the native JS implementation was more than 100% slower.

So why is it faster to use $ and return a new instance of jQuery.fn.init object, perform a bunch of find and filter tests and a lot of other operations (what jQuery does in effect), then execute one of its methods rather than look up a named function?

Was it helpful?

Solution

I see two mistakes in your jsperf as noted in comments as well:

  • jQuery is heavily optimized. .addClass will only add it if it isn't already added.

  • You don't check for it. You are just appending it using += which creates numerous string instances as it runs for 10,00 times or so, which even crashed my browser ;)

Dr.Molle's modified jsperf shows that by fixing the above things, it is the fastest.

Ah! Niet the Dark Absol has provided even a faster one here. It is fast because it uses native classList and doesn't manually checks for availability of the class.

OTHER TIPS

When doing test case, you need to be sure that

  • Both code does exactly the same;
  • There is no error (my browser crashed when running your test).

Now, i've replicated the exact same code that jQuery use to add class and in fact, vanilla JS is faster, by 100%:

JSPerf

The reason why are simples, less function call and less condition. When using jQuery, you use a function call to select an id: $('#id') and inside that function, you have some condition to check if it need to create a DOM element or use query selector... You can see the relevant code here.

Then after, the jQuery .addClass() also have condition since it is possible to use a function as argument. In those said condition, they use even more function call, slowing the process. Again, you can check the code here.

Now, JavaScript has evolve and it now have a build-in function to add remove classes. Niet the Dark Absol made a JSPerf with it. It is the fastest way to add class but why do jQuery doesn't use it? Simply because of the browser compatibility

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top