Reducing property access
Loops are generally not great from the performance perspective, but often times it’s relatively easy to pinpoint and optimize those inefficient function you wrote and call inside of a loop. But sometimes, especially with JavaScript, the functions causing the performance hit are the ones that are provided to you by language.
Let’s look at the most basic example of taking an array of items and adding them to your html table.
for (var i = 0; i < items.length; i++) {
document.getElementById("listGrid").innerHTML += "<tr><td>" +
items[i].name +
"</td></tr>";
}
This is pretty straight forward. Iterate through the array and inject each item name into a listGrid
table . There are no special functions to worry about, this loop is based purely on JavaScript-provided functions for doing exactly those things. And yet, there is still room for optimization.
Reduce property lookup overhead
First of all, let’s look at the loop definition itself. The instruction is to iterate from index 0 to last element of the loop, as defined by the array function length.
Problem here is that items.length
property is being accessed on every iteration of the loop, for really no reason. So let’s take it outside the loop.
var itemArrLen = items.length;for (var i = 0; i < itemArrLen; i++) {
document.getElementById("listGrid").innerHTML += "<tr><td>" +
items[i].name +
"</td></tr>";
}
Now, no matter how many elements are in that array, items.length
will only be looked up once.
Reduce DOM access
The other issue with the example code is the injection action itself. document.getElementById
traverses DOM with each loop iteration to find the same listGrid element every time. Instead, let’s just do the lookup once, store the element in a variable and use it in a loop for injection.
var itemArrLen = items.length;
var element = document.getElementById("listGrid");for (var i = 0; i < itemArrLen; i++) {
element.innerHTML += "<tr><td>" + items[i].name + "</td></tr>";}
Note, the same applies if you’re using jQuery (or other frameworks) instead of raw HTML for DOM manipulation. Remember, no matter how you to do DOM lookups — you’re still doing DOM lookups.