Tuesday, November 28, 2006

Measuring the CLR, using ILdasm

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/measuring_the_clr_using_idasm.htm]

I've been looking more at the .Net CLR, i.e. how .Net really works under the hood. Because most of my work and hobbies are application development, it's easy to take the CLR for granted.

I've been reading Don Box's (with Chris Sells) Essential .Net Volume 1: The Common Language Runtime. I'll try to blog more about each chapter as I read it. Obviously given the popularity of both authors, it's a good book. Even though it's for .Net 1.0, it's still very practical.

It makes it much easier to understand something if you can observe and measure a cause and effect. Many devs I see don't try to understand the CLR because they can't measure much about it - such as how much memory some code takes, how fast the code runs, what happens when it gets compiled, etc... For example, many devs use try-catch to do business logic checks, and don't worry about performance because it "works fast enough on my machine."

I'm no CLR guru (you can see the official Microsoft CLR bloggers here), but I'll be blogging my adventure digging deeper into the CLR.

To kick it off, I started with Ildasm (view MSDN tutorial here). As every .Net book points out, .Net languages (like C# and VB.Net) get compiled into MSIL - Microsoft Intermediate Language - or just IL for short. This allows .Net to be language independent, because no matter what language you code in, it gets compiled to the same IL. Ildasm lets you see that compiled IL.

First, you can see the IL Specification here.

You can run Ildasm by opening the VS command prompt and just typing "ildasm". If you go to File > Open, you can browse for an assembly, load it, and then view its IL and meta information.

Here are some immediate benefits of what you can see with IL:

  1. Whether this is a debug or release assembly - the Debug version will have an extra line:
        // .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute
  2. The meta data for the assembly (like company name)
  3. What other assemblies this one references.
  4. The actual IL. So, for example, you could see the number of boxing and unboxing operations by checking for the box and unbox IL commands.
  5. All the types and classes in the assembly.k

A super-version of IL, which can take an assembly and convert from the IL back to a .Net language is Lutz Roeder's Reflector. This is very useful for reverse engineering an assembly - even Microsoft's own system assemblies.

I'll blog more about this in my upcoming posts.

No comments:

Post a Comment