Tuesday, June 28, 2005

Code optimizations in C#

One of the code optimizations that we always do during code review process is to check for unnecessary range checks during a looping process. The following excerpt describes the CLR optimization process to eliminate the range checks. Note a slight deviation to the code as described below would stop CLR from eliminating the range checks thus causing poor performance.

Range Check Elimination
One of the many benefits of managed code is automatic range checking; every time you access an array using array[index] semantics, the JIT emits a check to make sure that the index is in the bounds of the array. In the context of loops with a large number of iterations and small number of instructions executed per iteration these range checks can be expensive. There are cases when the JIT will detect that these range checks are unnecessary and will eliminate the check from the body of the loop, only checking it once before the loop execution begins. In C# there is a programmatic pattern to ensure that these range checks will be eliminated: explicitly test for the length of the array in the "for" statement. Note that subtle deviations from this pattern will result in the check not being eliminated, and in this case, adding a value to the index.
Range Check Elimination in C#

//Range check will be eliminated
for(int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i].ToString());
}

//Range check will NOT be eliminated
for(int i = 0; i < myArray.Length + y; i++)
{
Console.WriteLine(myArray[i+x].ToString());
}

The optimization is particularly noticeable when searching large jagged arrays, for instance, as both the inner and outer loop's range check are eliminated.

Read more about Writing High Perofrmance Managed Applications here

0 Comments:

Post a Comment

<< Home