Friday, March 09, 2007

.NET compiled or interpreted?

How can C# be as fast as C++. C/C++ is compiled direct to machine code all the calls are linked at link time before the program is run Surely C# will be slower because code has to be compiled on the fly i.e. as it is executed. How can interpreted code be faster then pre compiled code?

This is true .NET assemblies do not contain machine code they contain a op codes similar to what a compiler generates in the form of MSIL (Microsoft Intermediate language). Microsoft provide a tool to view the MSIL in assemblies called ILDASM (Intermediate Language Disassembler)

The CLR reads this MSIL and “just in time” compiles into machine code on a method by method, call by call basis

The key thing to remember however is once. The CLR has JITTED the MSIL the machine code remains cached in memory if the same methods are called the CLR knows it has already compiled this code and will call the machine code directly. therefore .NET can not be considered as interpreted

Therefore yes the first c# call to a method will be slower but once it is JIT it will be just as fast as any other compiled method in C++ or C.

Note Microsoft provide a tool called NGEN which will actually compile and convert the MSIL assembly into native machine code. Please note that all the system .NET libraries provided by Microsoft in the GAC global assembly cache have already been NGEN and so are in native machine code. Before you go and NGEN all your assemblies consider that it may be slower for the CLR to load the entire assembly machine code rather then JIT the small portion of the code that gets called. Also bare in mind you are tying your assembly to a particular platform and processor architecture.

Have a read through

http://channel8.msdn.com/Posts/MSIL-the-language-of-the-CLR-Part-1

http://channel8.msdn.com/Posts/MSIL-the-language-of-the-CLR-Part-2

http://channel8.msdn.com/Posts/MSIL-the-language-of-the-CLR-Part-3

This article also goes into detail about the physical layout of an assembly

http://www.informit.com/articles/article.aspx?p=25350

1 Comments:

At 10:01 PM, Anonymous Anonymous said...

Great work.

 

Post a Comment

<< Home