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
- 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