Start on LCG

I think I will start severl topics around LCG in the furture. Our PM Joel has an excellent post about various method invocations and the paragraph about LCG is a sweet start point on Lightweight Code Gen.

Here is a list of basic dynamic features:

1. LCG Methods are reclaimable. 

   If you used Reflection.Emit, you will probably find that you cannot delete your emitted stuff within the same appdomain. It is because Reflection.Emit stuff lives on loader heap and those memories are not reclaimable until AppDomain shutdown. For dynamic method, it's code heap can be fully reclaimed through GC reclaim, and its method desc can be resued. So you can imagine that if you are emitting a lot of methods within an Appdomain using Reflection.Emit, even though you finished using most of them, the memory usage will increase linearly until you unload the appdomain. But for dyanmic method, if you are only holding up to a certain number of methods and creating and release a lot of methods, the memory usage will be flat.

2. LCG Method is a global static method on module.

   LCG Method is bascially a piece of code that has minimium amount of metadata associated with it. Although we have a Creation API that allows you to specify a parent type for the dynamic method, the type there is only used for visibility checks -- that is the dynamic method will be able to access all private members in the type and all internal members in the type's module. Metadata-wise, it doesn't belong to that type.

You can imagine then LCG Method's can be used to write compiled regular expression evaluator, XSLT transformation sheet, database queries. It provides an efficient way for server-side code generation. LCG methods can be invoked early bind (through Emit(OpCodes.Call, DynamicMethod)), late bind (DynamicMethod.Invoke) and through delegate.

Skip to main content