World of Web

Foreach vs. ToList()

by on Okt.05, 2010, under Kurztutorials

Problematik

Problem: Ein Array soll zu einer Liste werden.

Lösungen:

  1. Foreach
  2. ToList()-Extension

Der Vergleich der beiden Varianten:

Vergleich Foreach vs ToList - Hohe Werte

Foreach vs. ToList - Hohe Werte

Foreach vs. ToList - niedrige Werte

Foreach vs. ToList - niedrige Werte

x-Achse: Anzahl der Elemente

y-Achse: Zeit in ms

Codebeispiel

Der Code mit dem die Statistik erstellt wurde:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
List<TimeSpan> timeForeach = new List<TimeSpan>();
List<TimeSpan> timeToList = new List<TimeSpan>();
List<string> collection = new List<string>();
for (int j = 100; j < 20000000; j*=2)
{
   Guid[] guidList = new Guid[j];
   DateTime start = DateTime.Now;
   for (int i = 0; i < guidList.Length; i++)
   {
      guidList[i] = Guid.NewGuid();
   }
   DateTime end = DateTime.Now;
   TimeSpan diffGen = end - start;
   List<Guid> guidListForeach = new List<Guid>();
   start = DateTime.Now;
   foreach (Guid g in guidList)
   {
      guidListForeach.Add(g);
   }
   end = DateTime.Now;
   TimeSpan diffForeach = end - start;
   timeForeach.Add(diffForeach);
   List<Guid> guidListToList = new List<Guid>();
   start = DateTime.Now;
   guidListToList = guidList.ToList<Guid>();
   end = DateTime.Now;
   TimeSpan diffToList = end - start;
   timeToList.Add(diffToList);
}
Console.WriteLine("Average Foreach \t {0} ms", timeForeach.Average(=> s.TotalMilliseconds));
Console.WriteLine("Average ToList \t {0} ms", timeToList.Average(=> s.TotalMilliseconds));

Fazit

Bei einer hohen Anzahl von Werten in einem Array ist die ToList-Extension schneller als die Foreach-Variante. Bei wenigen Werten ist die Foreach-Lösung performanter.

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Post to Twitter Post to Plurk Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to MySpace Post to Ping.fm Post to Reddit Post to StumbleUpon

Share on Facebook




2 Comments for this entry

  • Maxwell

    Hello! Is it alright that I go a bit off topic? I am trying to view your website on my iPod Touch but it doesn’t display properly, do you have any suggestions? Cheers! Maxwell

    VA:F [1.9.22_1171]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.22_1171]
    Rating: 0 (from 0 votes)
    • h3mpti

      Hi,
      i installed a WordPress Mobile Plugin so that Mobile Devices should use another Theme. I hope this solves your problem.
      I’ll also try to provide the Articles in German and English soon. Sorry for your inconvenience.

      VN:F [1.9.22_1171]
      Rating: 0.0/5 (0 votes cast)
      VN:F [1.9.22_1171]
      Rating: 0 (from 0 votes)

Leave a Reply