Today, I will start a series of posts dedicated to javascript performance tricks and I will begin with some insights into javascript loops.
Let’s prepare the scenario:
var col = []; // array with 1000 items var t = 0; //counter //let's fill the array. for (var c = 999; c >= 0; c--) { col = c; };
This is how a traditional javascript loop looks like:
var t=0; for (var i = 0; i<= col.length; i++) { t++; };
Well, we have several options here to improve this loop. One of them is caching the value of the array length into a variable in order to stop this value from being evaluated in every loop’s iteration. Just like this:
var t=0; for (var i = 0, len=col.length; i<= len; i++) { t++; };
I have prepared this performance example for you to see the difference.
Now, I will show you yet another way to improve this loop that will work even faster in most browsers:
var t=0; for (var i = col.length;i>=0; i--) { t++; };
As you will be able to see here, reversed loops use to be the most efficient in almost any case.
At last, I will show you one of the most expensive loops you will find in javascript, so try not to use it unless necessary. We’re talking about the for in loop:
var t=0; for (var i in col) { t++; };