Saturday, September 25, 2010

C# Code Performance Measurement

Many times we need to check the performance of the our C# code. so following is the workaround with an example. ..
Most developers prefer to use a foreach loop than for loop because foreach is easier to use. This will however prove to be costly when working with collections with a large amount of data. Consider the below sample in which I am looping through the same datatable using for and foreach. Also check the time taken by each loop on Fig 1.0.
  static void Main(string[] args)
  {
      DataTable dt = PopulateData();
      Stopwatch watch = new Stopwatch();
  
      //For loop
      watch.Start();
      for (int count = 0; count < dt.Rows.Count; count++)
      {
          dt.Rows[count]["Name"] = "Modified in For";
      }
      watch.Stop();
      Console.WriteLine("Time taken in For loop: {0}", watch.Elapsed.TotalSeconds);
 
      watch.Reset();
      //Foreach loop
      watch.Start();
      foreach (DataRow row in dt.Rows)
      {
          row["Name"] = "Modified in ForEach";
      }
      watch.Stop();
      Console.WriteLine("Time taken in For Each loop: {0}", watch.Elapsed.TotalSeconds);
  
      Console.ReadKey();
  }

Fig 1.0
As you can see the foreach loop is slow, it takes almost double the amount of time as that of the for loop. This is because in the foreach loop dt.Rows will access all the rows in the datatable.
For bigger collections always use for loop in case if looping is required.

No comments:

Post a Comment