C# Compiler Optimization

Gaurav Sharma here, I’m a developer with the Information Security Tools team.

A couple of months back when I was trying to understanding the .NET compilation model I encountered an interesting thing. I created a small program to print an Int32 type array to a console. The code follows.

    1:  using System;
    3:  namespace Optimization
    4:  {
    5:    class Program
    6:    {
    7:      static void Main(string[] args)
    8:      {
    9:        Int32[] arr ={ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,11 };
   10:        for (Int32 i = 0; i<=arr.Length-1;i++) 
   11:        {
   12:          Console.WriteLine(arr[i]);
   13:        }
   14:        Console.ReadLine();
   15:      }
   16:    }
   17:  }


I then checked the IL that is generated from this small code snippet. I checked various function calls that were made by the C# compiler and noticed an interesting thing. The C# compiler had optimized the above code by intelligently adding new instructions and removing unnecessary instructions. The IL generated follows.


The compiler stores the array length in IL_0000. After this step, as you can see that there is no call made to Array.Length property i.e. get_Length() method.

Only three calls are added by C# compiler;

  1. Initialize Array
  2. Write Line, and
  3. Read Line

The C# compiler had optimized my code internally so that there is no need to call Array.get_Length() method with every loop iteration. It uses the Array Length stored in the beginning of the instruction set. So, if you are working on similar kind of code snippet then there is no need to declare a variable to store the array length just before the loop and use that variable in the loop condition check; the C# compiler does that for you in the background!

Now my Tip of the Day for writing better code with Visual Studio

No one likes unwanted using or Imports statement in the beginning of your C# or VB.NET code file. There is a quick solution for this:


Happy coding!