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
EasyCreate a method called optimizedSum that:
- Takes an array of integers as a parameter
- Calculates the sum of all elements
- Implements both an optimized and unoptimized approach:
- Unoptimized: Call array.Length in each loop iteration
- Optimized: Cache the length before the loop
- 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
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety