C# Programming Performance Tips - Part Six - Array Length

You can read all the C# performance tips from the following links,

Often, developers tend to use Array.Length in the For loop as a condition but we need to understand that the Lenth property is called on each and every iteration. So, it is better to store it in a variable and use that variable as a condition.

Array.Length in the loop

  1. Stopwatch watch = new Stopwatch();  
  2. watch.Start();  
  3. string[] names = {  
  4.     "Akshay",  
  5.     "Patel",  
  6.     "Panth"  
  7. };  
  8. for (int i = 0; i < names.Length; i++) {}  
  9. Console.WriteLine("Name.Length Direct-{0}", watch.Elapsed); 

Array.Length stored in a variable

  1. watch.Restart();  
  2. string[] names1 = {  
  3.     "Akshay",  
  4.     "Patel",  
  5.     "Panth"  
  6. };  
  7. int k = names1.Length;  
  8. for (int j = 0; j < k; j++) {}  
  9. Console.WriteLine("Name.Length Parameter-{0}", watch.Elapsed); 

Benchmarking Result

Array Length