You can read all the C# performance tips from the following links,
- C# Programming Performance Tips - Part One - String Split
- C# Programming Performance Tips - Part Two - String Equals
- C# Programming Performance Tips - Part Three - Adding Strings
- C# Programming Performance Tips - Part Four - List.Count() Vs List.Any()
- C# Programming Performance Tips - Part Five - List.Count() Vs List.Count
- C# Programming Performance Tips - Part Six - Array Length
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
- Stopwatch watch = new Stopwatch();
- watch.Start();
- string[] names = {
- "Akshay",
- "Patel",
- "Panth"
- };
- for (int i = 0; i < names.Length; i++) {}
- Console.WriteLine("Name.Length Direct-{0}", watch.Elapsed);
Array.Length stored in a variable
- watch.Restart();
- string[] names1 = {
- "Akshay",
- "Patel",
- "Panth"
- };
- int k = names1.Length;
- for (int j = 0; j < k; j++) {}
- Console.WriteLine("Name.Length Parameter-{0}", watch.Elapsed);
Benchmarking Result


Guest UserPosted Jul 28, 2020, 5:34 AM
Sorry, but this article is completely wrong. How can you possible expect reasonable results with just 3 values in just one run? There could be millions of other things your CPU was busy with at the time. You should change your benchmark to work with more than a million records, and run it many many times. You will find that the two approaches have the same time complexity. C# Array.Length is an O(1) operation, just like the cached variable approach.
Rajanikant HawaldarPosted May 16, 2019, 12:22 PM
Thanks for sharing