Search code examples
c#performancecil

Why Managed module Is faster than Unmanaged module in C#


I reading a book( CLR via c#)in the book writer speak about IL and managed module that managed module compiling in native cpu code and then execute in the book writer said that Managed module Is faster than Unmanaged module.my question is why Managed module Is faster than Unmanaged module but for in Managed module first compile to IL and then compile in native cpu.


Solution

  • (What I wrote below is not mine, it is copy-pasted from a book: CLR via C#, Page No 14)


    There are many reasons why a managed code can outperform unmanaged code

    When the JIT compiler compiles the IL code into native machine code at run time, the compiler knows more about the execution environment than an unmanaged compiler would know.

    Some ways in which managed code can outperform unmanaged code

    • A JIT compiler can determine if the application is running on an Intel Pentium 4 CPU and produce native code that takes the advantage of any special instruction offered by the CPU. Usually, unmanaged application are compiled for the lowest-common denominator of the CPU and avoid using special instruction that would give application performance boost.
    • A JIT compiler can determine when a certain test always fail on the machine that it is running on. Consider the example

      if (num_of_cpu > 1)
      {        
      }
      

    This code causes the JIT to not generate any CPU instruction if the machine has only One CPU.

    • The CLR could profile the code's execution and recompile the IL into a native code while the application runs. The recompiled code will be reorganized to reduce incorrect branch prediction depending on the observed execution patterns. Current version of C# do not do this, but future version might.