Dumping an Object's State with a DynamicMethod


In two prior articles, I talked about the general benefit of using Reflection. With Reflection, you can write a general solution, such as dumping an object's state, one time and it works for any object. The problem is speed. After that, I talked about writing a general solution that emits a specific solution. The benefit of Relection.Emit is speed. The problem with emitting a dynamic assembly is that it lingers around until your application shuts down. This could end up hogging needed resources. A best of class solution is to write a general solution that emits a specific typed-based solution based on MSIL but uses a DynamicMethod instead.

The new and improved DynamicMethod means that you can emit performant, dynamic MSIL but when the DynamicMethod goes out of scope so goes the emitted code. No more slow, generic Reflection code, and no more assemblies hanging around stinking up your memory.

Writing an Emitter Using a DynamicMethod

When you write an emitter that generates a dynamic assembly, you need an AssemblyName, AppDomain, AssemblyBuilder, and a TypeBuilder. After the TypedBuilder, you add behaviors to the type with a MethodBuilder. Using the DynamicMethod introduced in .NET 2.0, you start right off with the MethodBuilder. In the MethodBuilder, you add the same kind of code to generate the same kind of MSIL that you'd add to a dynamic assembly. The difference is that the DynamicMethod is designed to be unloadable after you are done using it even if your application is still running.

The code in Listing 1 creates a DynamicMethod. The DynamicMethod will contain emitted code that determines the type of an argument object and emits code that dumps the state of that object. The code is JIT (Just-In-Time) compiled; the result is that the first time a DynamicMethod is called, it is slow like plain old Reflection because you are paying for JIT compiling. Every subsequent time, the performance of the dynamic code is identical to literal hard code that performs the same task. Table 1 shows you comparisons among different kinds of implementations.

Listing 1: A DynamicMethod that emits code to dump a collection of object's and their state.

Imports System.Reflection.Emit
Imports System.Reflection
Imports System.IO

Module DynamicMethodCreator

   Public Function CreateDumpDelegate(Of T)(ByVal obj _
      As IEnumerable(Of T)) As DynamicMethod

      Dim method As DynamicMethod = New DynamicMethod( _
         "Dump" + GetType(T).Name, Nothing, _
         New Type() {GetType(IEnumerable(Of T)), _

      Dim write As MethodInfo = _
         GetType(Console).GetMethod("WriteLine", _
         New Type() {GetType(String)})

      Dim concat As MethodInfo = _
         GetType(System.String).GetMethod("Concat", _
         New Type() {GetType(String), GetType(String)})

      Dim MoveNext As MethodInfo = _
         GetType(System.Collections.IEnumerator). _
         GetMethod("MoveNext", New Type() {})

      Dim enumer As MethodInfo = _
         GetType(IEnumerable(Of T)).GetMethod("GetEnumerator", _
         New Type() {})

      Dim get_Current As MethodInfo = _
         GetType(System.Collections.IEnumerator). _
         ' get the properties and use them to build writeline
         ' statements
      Dim properties() As PropertyInfo = GetType(T).GetProperties()
      Dim generator As ILGenerator = method.GetILGenerator()

      Dim localT As LocalBuilder = _
      Dim localI As LocalBuilder = _
         generator.DeclareLocal(GetType(IEnumerator(Of T)))
      Dim localB As LocalBuilder = _
      ' Try
      generator.EmitCall(OpCodes.Callvirt, enumer, Nothing)
      Dim IL_000b As Label = generator.DefineLabel()
      Dim IL_003f As Label = generator.DefineLabel()
      generator.Emit(OpCodes.Br, IL_003f)    ' BR_S is wrong
      generator.EmitCall(OpCodes.Callvirt, get_Current, Nothing)
      ' Added this to convert object to type T
      generator.Emit(OpCodes.Castclass, GetType(T))
      ' write each property
      For Each prop As PropertyInfo In properties
         generator.Emit(OpCodes.Ldstr, prop.Name + "=")
         Dim get_Prop As MethodInfo = GetType(T).GetMethod("get_" _
            + prop.Name, New Type() {})
         generator.EmitCall(OpCodes.Callvirt, get_Prop, Nothing)

         If (prop.PropertyType.IsValueType) Then
            generator.Emit(OpCodes.Box, prop.PropertyType)
            generator.Emit(OpCodes.Callvirt, _
               GetType(Object).GetMethod("ToString", New Type() {}))
         End If

         generator.Emit(OpCodes.Call, concat)
         generator.Emit(OpCodes.Call, write)


      generator.EmitCall(OpCodes.Callvirt, MoveNext, Nothing)
      ' Brtrue_S is wrong
      generator.Emit(OpCodes.Brtrue, IL_000b)
      Dim IL_0060 As Label = generator.DefineLabel()
      generator.Emit(OpCodes.Leave_S, IL_0060)
      ' begin finally
      Dim IL_005e As Label = generator.DefineLabel
      generator.Emit(OpCodes.Brfalse_S, IL_005e)
      Dim dispose As MethodInfo = _
         GetType(System.IDisposable).GetMethod("Dispose", New Type() {})
      generator.EmitCall(OpCodes.Callvirt, dispose, Nothing)
      Return method

   End Function
End Module

Table 1: Comparing algorithms and relative performance

Solution General Use Relative Speed JIT Compile Assembly Unloaded
Hard Code No Fast No N/A
Reflection Yes No No N/A
Reflection Emit Yes Yes Yes No
DynamicMethod Yes Yes Yes Yes




Dumping an Object's State with a DynamicMethod

Using the DynamicMethod State Dumper



Listing 2: Sample code to use the DynamicMethod.

Imports System.Reflection
Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Reflection.Emit

Module Module1

   Sub Main()

      ' Create customer list
      For i As Integer = 0 To 50
         customers.Add(New Customer(i.ToString()))

      Dim method As DynamicMethod = _
      MyDelegate = method.CreateDelegate( _
         GetType(DumpDelegate(Of Customer)))
      MyDelegate(customers, Console.Out)

   End Sub

   Private MyDelegate As DumpDelegate(Of Customer)
   Private Delegate Sub DumpDelegate(Of T)( _

End Module




About the Author






Leave a Comment

Top White Papers and Webcasts


Most Popular Programming Stories

More for Developers

RSS Feeds
