DEV Community

Cover image for Tips To Handle Performance And Coding Way Between Different Type Of Loop ( For, Foreach, While…)
Kareem Zock
Kareem Zock

Posted on

Tips To Handle Performance And Coding Way Between Different Type Of Loop ( For, Foreach, While…)

In this article, you will learn how to use loops and how to handle it's performance.

Different Types of Loops in coding:
PS: syntax may differ between language and another but in this article, we are talking about it more in generic.

Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save time and effort.

while — loops through a block of code as long as the condition specified evaluates to true.

while(condition){
// Code to be executed
}

do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.

do{
// Code to be executed
}

while(condition);`

for — loops through a block of code until the counter reaches a specified number ( 10 times, 20 times, 100 times..)

for(initialization; condition; increment){
// Code to be executed
}

foreach — loops through a block of code for each element in an array.

foreach($array as $value){
// Code to be executed
}

Loop Optimization tips:

1- Consider defining the size and use it variable within the for loop:

int size = data.size(); for (int i = 0; i < size; i++) { ... }

2- Using Foreach or an Iterator is better and faster in performance than for loop:

foreach($array as $value){
// Code to be executed faster then a for loop like for(int i=0; i < size;i++){}
}

Some tips after testing for loop speeds

  • while loops scale the best for large arrays.

  • for...of loops are hands down the fastest when it comes to small data sets, but they scale poorly and slow for large data sets.

  • .forEach() is close enough that neither side should hang their hat on performance alone over the other.

  • The execution time of .forEach() is dramatically affected by what happens inside each iteration but it's considerable fast in processing data.

  • Standard for loops had medium speed across the board.

But after all, using for loop type might also depend on what kind or size of data you're processing from large, small amounts of data or even specific numbers like 10, 100, or 1000.

Can be found also on Techwebies

Top comments (0)