Most efficient way for looping elements in JavaScript?
Sometimes you are in situation when your script really has to be efficient. If you are looping a large set of data, e.g. an Array of one million elements, you can gain (and lose) seconds depending on your choice of looping. First of all, create a good test data, an array with one million elements. We are not spending a lot of time with this, just using the fastest solution.
var test_data = []; for (var i=0;i<1000000;i++) { test_data.push(i); }
Lets see the general way of looping in javascript, using a for loop. Check how we are saving the length of the array into a variable, so we don't have to query it in each cycle.
var test_data_length = test_data.length; for (var i=0;i<test_data_length;i++) { //do something with the data }
For one million data, it took me about 963 ms, which is almost a sec. Too bad...
Let's see an other solution, Array.prototype.forEach(). It is supported by almost every new browser, in Internet Explorer only from version 9.
test_data.forEach(function(item){ //do something with the data });
This one took only 69 ms to finish, which is only 7% of the original time, which also means it is more than 10x faster!












