Difference between For and Foreach Loop in C# [Note]

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.
There is need to specify the loop bounds( minimum or maximum).

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. You do not need to specify the loop bounds minimum or maximum.

foreach: Treats everything as a collection and reduces the performance. foreach creates an instance of an enumerator (returned from GetEnumerator()) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.

Using for loop we iterate the array in both direction, that is from index 0 to 9 and from 9 to 0.

But using for-each loop, the iteration is possible in forward direction only.

In variable declaration, foreach has five variable declarations (three Int32 integers and two arrays of Int32) while for has only three (two Int32 integers and one Int32 array).

When it goes to loop through, foreach copies the current array to a new one for the operation. While fordoesn’t care of that part.

For and foreach differ slightly in performance. They are approximately the same speed. But the foreach loop uses more stack space for local variables.

In micro-benchmarking, introducing extra local variables with foreach-loops can impact performance. However, if those local variables are reused several times in the loop body, they can lead to a performance improvement.

The for-loop is faster than the foreach-loop if the array must only be accessed once per iteration.


Please follow and like us:

Leave a reply

Your email address will not be published.