Attending a great “Designing .NET Class Libraries” class run by Brad Abrams today.

I was surprised to see a coding pattern that I would commonly use in C++ and be told that was NOT the best way to do this in C#.

int len = array.Length();
for ( int i=0; i<len; i++ )
{
    array[i] = 0;
}

In C++, there's a performance gain in this example because the array Length() member is only called once and the value is cached for use inside the loop.

Apparently, because of how the JIT compiler unrolls loops and optimises bounds checking, the following pattern is going to produce more eficient code in C#, even though my C++ 'brain' says otherwise.

for ( int i=0; i<array.Length(); i++ )
{
    array[i] = 0;
}

This highlights my lack of C# knowledge since my initial response is to fallback to what I know best, which is C++. This is perfectly natural, since I'm still working at becoming an expert at C#, and the ease of use gained by C# and .NET comes with a price - handing over more responsibility to the C# compiler and .NET libraries. In making the move to C#, I need to leave behind my knowledge of Visual C++ optimization techniques and learn more about what the C# compiler is doing under the cover.

I need to learn some new tricks. I'm going to start by going over to the MSDN library and reading some of the performance related .NET Development articles, such as “Performance Considerations for Run-Time Technologies in the .NET Framework“.