Advertisement
SebastianLague

Foreach/For loop performance test

Mar 15th, 2016
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.61 KB | None | 0 0
  1. void Test() {
  2.     System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch ();
  3.     int repetitions = 1000000;
  4.     int subreps = 10;
  5.  
  6.     List<int> list = new List<int> ();
  7.     for (int i = 0; i < repetitions; i++) { // populate list
  8.         list.Add (0);
  9.     }
  10.  
  11.     sw.Start ();
  12.     for (int i = 0; i < repetitions; i++) {
  13.         for (int j = 0; j < subreps; j++) {
  14.             int x = list [i];
  15.         }
  16.     }
  17.     print("for loop: " + sw.ElapsedMilliseconds + "ms");
  18.  
  19.     sw.Reset ();
  20.     sw.Start ();
  21.  
  22.     foreach (int i in list) {
  23.         for (int j = 0; j < subreps; j++) {
  24.             int x = i;
  25.         }
  26.     }
  27.     print("foreach loop: " + sw.ElapsedMilliseconds + "ms")
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement