Saturday, July 25, 2020

Difference : for and foreach




For:
 for(int i=0; i<1000; i++){
}
The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.
There is a need to specify the loop bounds (minimum or maximum).
 Following is a code example of a simple for loop that starts 0 till <= 5.
foreach :
          foreach (var item in collection)
            {
              //  slow compare to for loop .
            // not allow to item modifications 
            }
we look at foreach in detail. 
What looks like a simple loop on the outside is actually a complex data structure called an enumerator:
An enumerator is a data structure with a Current property, a MoveNext method, and a Reset method. The Current property holds the value of the current element, and every call to MoveNext advances the enumerator to the next item in the sequence.
Enumerators are great because they can handle any iterative data structure. In fact, they are so powerful that all of LINQ is built on top of enumerators.
But the disadvantage of enumerators is that they require calls to Current and MoveNext for every element in the sequence. All those method calls add up, especially in mission-critical code.


No comments:

Post a Comment