[c#] What is the difference between for and foreach?

I prefer the FOR loop in terms of performance. FOREACH is a little slow when you go with more number of items.

If you perform more business logic with the instance then FOREACH performs faster.

Demonstration: I created a list of 10000000 instances and looping with FOR and FOREACH.

Time took to loop:

  • FOREACH -> 53.852ms
  • FOR -> 28.9232ms

Below is the sample code.

class Program
{

    static void Main(string[] args)
    {
        List<TestClass> lst = new List<TestClass>();
        for (int i = 1; i <= 10000000; i++)
        {
            TestClass obj = new TestClass() {
                ID = i,
                Name = "Name" + i.ToString()
            };
            lst.Add(obj);
        }

        DateTime start = DateTime.Now;
        foreach (var obj in lst)
        {
            //obj.ID = obj.ID + 1;
            //obj.Name = obj.Name + "1";
        }
        DateTime end = DateTime.Now;
        var first = end.Subtract(start).TotalMilliseconds;

        start = DateTime.Now;
        for (int j = 0; j<lst.Count;j++)
        {
            //lst[j].ID = lst[j].ID + 1;
            //lst[j].Name = lst[j].Name + "1";
        }
        end = DateTime.Now;
        var second = end.Subtract(start).TotalMilliseconds;
    }
}

public class TestClass
{
    public long ID { get; set; }
    public string Name { get; set; }
}

If I uncomment the code inside the loop: Then, time took to loop:

  • FOREACH -> 2564.1405ms
  • FOR -> 2753.0017ms

Conclusion
If you do more business logic with the instance, then FOREACH is recommended. If you are not doing much logic with the instance, then FOR is recommended.

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to foreach

Angular ForEach in Angular4/Typescript? How to use forEach in vueJs? Python foreach equivalent Get current index from foreach loop TypeScript for ... of with index / key? JavaScript: Difference between .forEach() and .map() JSON forEach get Key and Value Laravel blade check empty foreach Go to "next" iteration in JavaScript forEach loop Why is "forEach not a function" for this object?