Performance test:
Code Snippet
- class Program
- {
- static void Main(string[] args)
- {
- List<int> list= new List<int>();
- for(int i =0; i < 10000000 ; i++)
- {
- list.Add(i);
- }
- int sum = 0;
- Stopwatch sw = new Stopwatch();
- sw.Start();
- for (int i = 0; i < list.Count; i++)
- {
- sum += list[i];
- }
- sw.Stop();
- Console.WriteLine(" FOR {0}", sw.Elapsed.ToString());
- sw.Reset();
- sum = 0;
- sw.Start();
- foreach (int item in list)
- {
- sum += item;
- }
- sw.Stop();
- Console.WriteLine(" FOREACH {0}", sw.Elapsed.ToString());
- sw.Reset();
- Console.ReadLine();
- }
- }
10 items:
FOR 00:00:00.0000040
FOREACH 00:00:00.0000018
1000 items:
FOR 00:00:00.0000131
FOREACH 00:00:00.0000098
100 000 items:
FOR 00:00:00.0010038
FOREACH 00:00:00.0007952
10 000 000 items:
FOR 00:00:00.1031941
FOREACH 00:00:00.0819216
Conclusion:
When you don't need to manipulate items in collection, use Foreach, otherwise For.
Žiadne komentáre:
Zverejnenie komentára