2008-10-16
| Table of Contents: |
| Rate This Article: | Add This Article To: |
( Page 1 of 4 )
Dynamic methods have some powerful uses. Paul Kimmel shows you how to take them to the next level.
Until .NET 2.0, when emitting MSIL (Intermediate Language) by the Reflection namespace, you were required to generate a dynamic assembly and dynamic type to contain a method. Once created in memory these dynamic assemblies just hung around. In .NET 2.0 the DynamicMethod was introduced. Dynamic methods are loaded in memory like an emitted assembly but with the DynamicMethod the emitted code is unloaded when the DynamicMethod goes out of scope.
DynamicMethods are the most efficient way to emit dynamic MSIL because they requires less coding of Reflection.Emit elements and DynamicMethods can be compiled, executed, and discard by the garbage collector at runtime. No more lingering emitted assemblies.
Why would you use DynamicMethods? Consider some examples. First, assume you are using reflection to dump an object’s state or write a generic deep-copy behavior. You pass in the target object, reflect its properties, and perform the operation. This is a one-size method fits all. The problem is that the performance is substantially worse than hard-coded methods that do the same work. The problem with hard-coded methods—for dumping or deep copying or whatever you might do with Reflection—is that you have to write one method for each type. So you choices are write one slow method using Reflection or write many fast, hard—coded methods. Those were your choices until DynamicMethod showed up.
Using a DynamicMethod you can take the middle road. You can spend a little extra time writing a general emitter that emits hard-coded solutions that run as fast as hard-coded versions. That is, write one, general use algorithm that emits the equivalent of hard-coded, individuated solutions. The example demonstrated is an emitter that writes a dynamic deep copy method. For comparison purposes there are three examples that perform approximately the same task. There is a hard-coded deep copy that copies one kind of object. There is a hard-coded deep-copy version that deep copies any object using Reflection, and there is an emitter that emits a specific purpose deep copy method for any type. The Stopwatch class is used to let you compare the differences in performance.
![]() |
|


