Menu
Coddy logo textTech

Loop Performance

Part of the Logic & Flow section of Coddy's C# journey — lesson 13 of 66.

Optimizing loop performance can significantly improve your application's speed, especially with large data sets.

Store the collection length in a variable before the loop:

int[] numbers = { 1, 2, 3, 4, 5 };
int length = numbers.Length; // Store length once

for (int i = 0; i < length; i++) // Use stored value
{
    Console.WriteLine(numbers[i]);
}

Avoid repeated method calls in loop conditions, for example:

for (int i = 0; i < GetCount(); i++)
{
    // Loop body
}

The GetCount() method is called at every iteration of the loop. This means that if the loop runs 1000 times, GetCount() will be executed 1000 times as well, because the loop condition is evaluated before each iteration.

Here is how to do it correctly:

int count = GetCount();
for (int i = 0; i < count; i++)
{
    // Loop body
}

GetCount() is called only once before the loop starts, and its value is stored in the count variable. Then the loop uses this stored value for all iterations, eliminating the need to repeatedly call the method.

This approach can make your code run faster by reducing redundant operations, especially when the method being called performs complex calculations or data access.

challenge icon

Challenge

Easy

Create a method called optimizedSum that:

  1. Takes an array of integers as a parameter
  2. Calculates the sum of all elements
  3. Implements both an optimized and unoptimized approach:
    • Unoptimized: Call array.Length in each loop iteration
    • Optimized: Cache the length before the loop
  4. Returns the result from the optimized approach

Cheat sheet

Store collection length in a variable before the loop to avoid repeated property access:

int[] numbers = { 1, 2, 3, 4, 5 };
int length = numbers.Length; // Store length once

for (int i = 0; i < length; i++) // Use stored value
{
    Console.WriteLine(numbers[i]);
}

Avoid repeated method calls in loop conditions by caching the result:

// Inefficient - method called every iteration
for (int i = 0; i < GetCount(); i++)
{
    // Loop body
}

// Optimized - method called once
int count = GetCount();
for (int i = 0; i < count; i++)
{
    // Loop body
}

Try it yourself

public class OptimizedSum
{
    // Implement the optimizedSum method
    public static int optimizedSum(int[] numbers)
    {
        // Write your code here
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow