Performance Check On Different Type Of For Loops Available In The Javascript
For loops plays a major role in the software development irrespective of any programming language and a small mistake in the loop might collapse the entire application so we should be really careful while handling for loops.
In this post, We will look into different for loops and performance of each for loops available in the javascript. To Measure the performance we are going to use jsperf.
Description of jsperf as mentioned on their website.
jsPerf — JavaScript performance playground!!
jsPerf aims to provide an easy way to create and share test cases, comparing the performance of different JavaScript snippets by running benchmarks.
Let’s check different for loops available in the Javascript and finally, we will analyze the performance of each code snippet.
for loop
Ordinary for loop, Based on the length we will iterate through each element and we will access it using its index.
var loopArrayVariable = new Array(10000);
loopArrayVariable.fill(1); for (i = 0; i < loopArrayVariable.length; i++) {
console.log(loopVariable);
}
Note: If the loop is not proper we may end up in accessing data with out of the bound index.
for…each
Using for..each we can iterate through each and every element in an array. Easy to use.
var loopArrayVariable = new Array(10000);
loopArrayVariable.fill(1); loopArrayVariable.forEach(function(loopVariable){
console.log(loopVariable);
});
for…of
The for…of statement creates a loop iterating over iterable objects.
var loopArrayVariable = new Array(10000);
loopArrayVariable.fill(1); for (let loopVariable of loopArrayVariable) {
console.log(loopVariable);
}
for…in
The for…in statement iterates over the enumerable properties of an object.
var loopArrayVariable = new Array(10000);
loopArrayVariable.fill(1); for (let loopVariable in loopArrayVariable) {
console.log(loopVariable);
}
Performance Results
To check the performance, I have implemented 10000 iterations on above for loop types.
Based on Jsperf emulation performance result.
- for…in
- for…of
- for…each
- ordinary for loop
Conclusion
There are different types of for loops available with ES6 Standards. the for…of statement should be preferred whenever possible.
Even though for…in statement got better performance, it includes few unwanted prototypes properties so it should not be used for looping.
Prefer for…of over for…in whenever possible.
Want to some more best practices in Javascript. check here.
If you enjoyed this article, please share with your developer friends. Thanks for reading.