Two ways to drastically improve the speed of your jQuery code

jQuery is often looked at synonymously with JavaScript; although jQuery is just a library wrapper around native JavaScript. While jQuery is easier to some degree, a lot of the tutorials and examples on the internet showcase code that isn’t nearly as performant as using native JavaScript APIs. Although I do not suggest you use jQuery in your application, it has its merit and advantages. Here are just two examples of how you can improve the performance of your jQuery code drastically.

Looping

jQuery promotes the use of the .each() method for looping through DOM elements. It turns out that this is actually up to 10x SLOWER than using native JS’s for loop. Why? jQuery’s each method expects a function that gets called for each iteration, while the native JS just accesses the index of the array. Stick to using the native for loop! Here is a fiddle to demonstrate this: https://jsfiddle.net/r4xk1kw3/1/

Selecting Elements from the DOM

I’ll admit, the syntax for selecting DOM elements is much easier using jQuery, but it turns out that is is much less performant than using native JS. In fact, natively there are two ways to select elements by classname: 1) .querySelectAll() or 2) getElementsByClassName(). It turns out that getElementsByClassName() is the fastest way to get a list of elements, but jQuery’s selector engine is terribly slow. Here is a fiddle I made to demonstrate this: https://jsfiddle.net/yc09s6tf/1/

 

But Tom, that’s so ugly! Why would I ever want to write code like that? I’ll admit, native JavaScript code can be pretty fugly sometimes. But we can add a little syntactic sugar on top of the native code, while maintaining the majority of the performance gains. Here is a little utility function you can use to implement jQuery-like selectors in your code.

So what now?

Try out the fiddles for yourself and see how big of a difference these two changes can make. jQuery is nice on the eyes, but I hope you’re no longer surprised on how much faster native JavaScript is.