JavaScript For Loop Performance

A while back I wrote about creating HTML tables for tabular data and then using the jQuery plugin jEditable to allow inline editing of that table. The approach works well over all but there’s two areas where it falls apart – when the table has a large number of rows and when using older browsers (especially IE).

My first take on writing a framework to render the HTML table was in JavaScript. I liked it because everything was in JavaScript except the data access layer. However, when the table has a large number of rows, rendering it in the browser doesn’t work well – especially when your most commonly used browser is IE 8.

While IE 8 is an improvement over IE 6 & 7, it is still pitifully slow in executing JavaScript. I learned this after the fact, when I can a complete framework. It wasn’t too apparent with just one or two grids on the page, but when I had five grids and each at least several rows, IE 8’s slowness became painfully apparent. So, off to do a deep dive into JavaScript performance in IE 8.

My  approach had been to make an AJAX call, retrieve a DataTable that was converted to JSON and then loop through that on the client, gradually building out the HTML table. One of the first performance issues I found was the wide variety of JavaScript loops and their various speeds. It turns out that while IE 8 is very slow over all, there are several JavaScript loops that are really slow.

Here are two different benchmarks for JavaScript For Loops:

Check them out; I’ll wait.

Notice the graphs for IE 6, 7, or 8? They barely even register on the overall graph. If you are interested in specific loop performance, you can run the test and see the operations per second number.

What I found was that in IE 8, for…in loops only where clocking in at around 150 ops/sec. While modern Chrome and Firefox were in the thousands. This was a bit frustrating because the for…in loops made it really easy to work with the JSON that was being return to the client. Foreach loops and jQuery loops were also quite bad.

So my rule of thumb going forward, is to use just a plain, native for loops. At least in the older IE browsers, they represented the fastest possible execution times.


Share this Story:
  • facebook
  • twitter
  • gplus

About Jeremy Foltz

Leave a comment