
Languages That Support Late-Bound Calls
Dynamic methods are useful to compiler writers when the type of an object is not known at compile time. Calls to the object's members must be resolved at run time, frequently with the additional overhead of manipulating argument lists. The following Visual Basic code provides an example of this.
Sub Example(ByVal obj as Object)
' ...
obj.SomeMethod(x, y, z)
' ...
End Sub
The compiler must generate code to look up SomeMethod, prepare the arguments as an array of objects, and invoke the method. Executing such calls with reflection, using the InvokeMember method, does not provide good performance. Performance can be improved by using members of the System.Reflection.Emit namespace to create a dynamic assembly, module, type, and method, but this can result in a larger working set and greater code complexity. Dynamic methods allow a more efficient implementation strategy in cases where the dynamic method signature matches an existing delegate type, because there is no need to create a dynamic assembly, module, or type. This approach performs much better than using the InvokeMember method. It does not perform as well as a virtual call, but it requires a much smaller working set because no new types are created. Furthermore, the generated MSIL and associated native code can be reclaimed when no longer needed.