May 30, 2011

Managed Versus Unmaged Code

The only main difference between managed and unmanaged code is that in managed code, the memory is managed. That is, in general, something called as 'The Garbage Collector' takes care of memory allocation and deallocation; Garbage Collector(GC) is a part of the compiler. In other words, memory management is done by software. In an unmanaged code, the programmer should take care of memory management.

We can also say that by managing memory through software, pointer concepts can be almost completely eliminated. I use 'almost' here because some languages, like C#, which produces managed code allows pointers. Programmers who are comfortable with C or C++ or similar languages may feel that eliminating pointers is like cutting an hand off. But pointers really make a programmer's life, 'a living hell'. They are the main source of memory leaks. Even security can be compensated. Using pointers, we can even completely corrupt the entire system, accessing critical memories of the system.

But some critics say that unmanaged code runs faster than managed code. The main reason for that is, on compilation, unmanaged code generates raw machine level instructions but a managed code generates an intermediate file that contains instruction from something called as the 'Intermediate Language(IL)'. This intermediate file is then interpreted by a 'Virtual Machine(VM)', that executes machine level instructions corresponding to the IL instructions. That is, the main job of a VM is to map IL instructions to machine level instructions. The other jobs of VM are to perform GC, and compile some IL instructions to machine level instructions(this process is done by a software popularly called as just-in-time compiler or jitter).

I previously mentioned that GC is part of compiler. But the actual garbage collection is performed by the VM. The job of the compiler is to introduce GC related instructions in the intermediate file. The VM can then use these 'GC instructions' to do garbage collection. The VM is also the main 'thing' that makes a language 'platform independent' like Java or 'language independent' like .NET aware languages.

Examples of languages generating unmanaged code: C, C++.
Examples of languages generatinf managed code: Java, .NET aware languages like C#, A#, F#, E#.