title: Performance analyze for loop and foreach
body: <p>In this thread we discussed about performance analysis of the <code>for loop</code> and <code>foreach</code>.
  Which one gives better performance - the <code>for</code> or <code>foreach</code>?</p>
  
  <p>Here are two simple methods: </p>
  
  <pre><code> public static void TestFor()
  {
  
      Stopwatch stopwatch = Stopwatch.StartNew();
      int[] myInterger = new int[1];
      int total = 0;
      for (int i = 0; i &lt; myInterger.Length; i++)
      {
          total += myInterger[i];
      }
      stopwatch.Stop();
      Console.WriteLine("for loop Time Elapsed={0}", stopwatch.Elapsed);
  }
  public static void TestForeach()
  {
      Stopwatch stopwatchForeach = Stopwatch.StartNew();
      int[] myInterger1 = new int[1];
      int totall = 0;
      foreach (int i in myInterger1)
      {
          totall += i;
      }
  
      stopwatchForeach.Stop();
      Console.WriteLine("foreach loop Time Elapsed={0}", stopwatchForeach.Elapsed);
  }
  </code></pre>
  
  <p>Then I ran the above code the result was foreach loop Time Elapsed=00:00:00.0000003,
  for loop Time Elapsed= 00:00:00.0001462. I think we want high performance code. We would use foreach</p>