Thomas R Alexander

Manager, Developer, and professional problem solver

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.


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:

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:


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.


Leave a Reply

Your email address will not be published. Required fields are marked *.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">