In this article in the optimizing .NET code series, we’ll discuss “Iteration and Looping”. Non-optimized code within loops can lead to performance issues, ranging from increased memory consumption to CPU exhaustion. This section summarizes guidelines that will improve iteration and loop efficiency:
Avoid Repetitive Field or Property Access
If your data is static for the duration of the loop, obtain it before the loop instead of repeatedly accessing a field or property. The following code shows a collection of orders being processed for a single customer.
for ( int item = 0; item < Customer.Orders.Count ; item++ ){
CalculateTax ( Customer.State, Customer.Zip, Customer.Orders[item] );
}
Note that State and Zip are constant for the loop and could be stored in local variables rather than accessed for each pass through the loop as shown in the following code.
string state = Customer.State;
string zip = Customer.Zip;
int count = Customers.Orders.Count;
for ( int item = 0; item < count ; item++ )
{
CalculateTax (state, zip, Customer.Orders[item] );
}
Note that if these are fields, it may be possible for the compiler to do this optimization automatically. If they are properties, it is much less likely. If the properties are virtual, it cannot be done automatically.
Optimize or Avoid Expensive Operations Within Loops
Identify operations in your loop code that can be optimized. Look for code that causes boxing or allocations as a side effect. The following code causes side effect strings to be created for each pass through the loop.
Read the full post








