C# foreach vs for performance(Examples to compare their efficiency)

Lionsure 2020-07-21 Original by the website

I have seen a lot of articles about the efficiency of for and foreach on the Internet. Some say that for is efficient, and some say that foreach is efficient. I think it's a bit one-sided to say who is more efficient, because different situations will produce different results; for may be more efficient than foreach in some aspects, and foreach is more efficient than for in other aspects. Here are two examples, one is to find a string, the other is to find an integer.

 

Examples of C# foreach vs for performance

1. Search string

The program composes a list by continuously generating random strings, and then searches for "abc" from the list, and then jumps out of the loop when found. The specific code is as follows:

// C# foreach vs for performance
       public void for_foreach()
       {
              IList<string> list = new List<string>();
              string str = "agfeywskjfjdks;glywiiraqeopmnbvcxz";
              for (int i = 0; i < 100000; i++)
                     list.Add(Randoms(str, 3));

       int count = list.Count;
              Stopwatch sw = new Stopwatch();

       sw.Start();
              for (int i = 0; i < count; i++)
              {
                     if (list[i] == "abc")
                            break;
              }
              sw.Stop();
              lblRunTime.Text += "for time: " + sw.ElapsedMilliseconds;

       sw.Reset();
              sw.Start();
              foreach(string s in list)
              {
                     if (s == "abc")
                            break;
              }
              sw.Stop();
              lblRunTime.Text += "; foreach time: " + sw.ElapsedMilliseconds;
       }

//Generate random numbers
       public string Randoms(string c, int n)
       {
              StringBuilder sb = new StringBuilder(n);
              int oneNum;
              Random rnd = new Random();
              for (int i = 0; i < n; i++)
              {
                     oneNum = rnd.Next(c.Length);
                     sb.Append(c[oneNum]);
              }
              return sb.ToString();
       }

 

The following are several sets of running time-consuming data(unit: ms):

for time: 2; foreach time: 3;

for time: 4; foreach time: 6;

for time: 3; foreach time: 4;

for time: 5; foreach time: 4;

for time: 2; foreach time: 2;

It can be seen from comparison that for takes about less time than foreach. Only one group takes the same time. One group is that foreach takes less time than for. Generally speaking, for is more efficient than foreach.

 

2. Find an integer

The program adds integers to the list through a for loop, then searches for 99999 from the list, and exits the loop if it finds. The specific code is as follows:

// C# foreach vs for performance
       public void for_foreach_num()
       {
              IList<int> ls = new List<int>();
              for (int i = 0; i < 100000; i++)
                     ls.Add(i);

       int n = ls.Count;
              Stopwatch sw = new Stopwatch();
              sw.Start();

       for (int i = 0; i < n; i++)
              {
                     if (ls[i] == 99999)
                            break;
              }
              sw.Stop();
              lblRunTime.Text += "for time: " + sw.ElapsedMilliseconds;

       sw.Reset();
              sw.Start();
              foreach (int i in ls)
              {
                     if (i == 99999)
                            break;
              }
              sw.Stop();
              lblRunTime.Text += "; foreach time: " + sw.ElapsedMilliseconds;
       }

The time-consuming results of several groups of running are as follows(unit: ms):

for time: 1; foreach time: 2

for time: 2; foreach time: 2

for time: 2; foreach time: 3

for time: 1; foreach time: 3

It can be seen from comparison that among the four sets of data, only one set has the same time, and the other three groups are for about less time than foreach, that is, for is about more efficient than foreach.

 

The above examples are that for is about more efficient than foreach, but this does not mean that for is dominant in all cases. In fact, when the number of loops is not too high, the difference in efficiency is completely negligible; if you encounter a particularly large data set during the programming process, and you cannot decide whether to use for or foreach, you can test their efficiency first. Relieve your worries.