jQuery Performance: for vs $.each
So you are using jQuery, pretty much everyone is using it (no stats to back this up, but it’s used a lot), and it’s full of awesome stuff. With jQuery, like many other languages it’s also possible to write code that can get you the end result in multiple ways. But is it the most efficient way?
Back a year or so ago, I would of been the one who was saying it’s fine just use the jQuery functions they are nice and easy, it can not be that bad. But since working on some big web apps with hundreds of thousands of users actively using the apps on a daily basis and spending a large chuck of their time doing meaningful work in them. I have started taking a really hard look into the way I am writing jQuery and the performance of the jQuery functions I am using.
A while back I was implementing a bit of custom functionality into a web app, where users could filter rows in a table using an input box, sort of like a live search. The more they type the more rows disappeared. Sounds straight forward enough, but the table is up over a hundred rows and has around 5 or 6 columns.
The code was first implemented using the jQuery $.each function to loop over the rows and determine if the value entered in the search box matched something in the row, if it did cool, if not hide the row. Again sounds straight forward. All seemed to work with the code for a little while, but over time, and when more rows where added and the complexity of the search grew the speed dropped very quickly and at some points there was lots of browser lag and sometimes the browser would crash.
I re-wrote the $.each to use a for loop and the code works perfect. This lead me onto to do some research into it.
While for the most part the developer who is doing stuff for their personal site or a site for the local business down the road, would not hit the issues I was having with my code in this scenario I found it intriguing at how much faster the native for loop was.
Think of it this way, as the native loop is nearly twice as fast that means I could do the same loop nearly twice, by the time jQuery would have done it once, making not only the site faster, but taking strain away from the browser and giving the user a faster and more tolerable user experience.
Note I am not suggesting that jQuery do not pay attention to performance far from it, John Resig and the jQuery core developers put a lot of effort into jQuery and I don’t mean to take anything away for that.
But sometimes you are simply not able to match the native speed using a wrapper. I working in jQuery on a near daily basis and love what they have done.