[Mono-list] Speed of MethodInfo.Invoke?
Jonathan Pryor
jonpryor at vt.edu
Fri Jan 27 20:33:03 EST 2006
On Fri, 2006-01-27 at 08:50 -0500, Chad Robinson wrote:
> I have a question about Mono internals (or CLR internals?). How is
> MethodInfo.Invoke actually implemented? I'm trying to write an extensible
> application that would support loading custom modules in external DLLs.
> However, the application is also tightly performance constrained. I guess what
> I'm asking is, what is the overhead like for invoking a method discovered
> through MethodInfo (assume I discover in advance, assume 2-3 object ref
> params) vs. a traditional call?
This was done under .NET, but I doubt that mono is significantly
different for relative performance:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp02172004.asp
http://blogs.msdn.com/ericgu/archive/2004/03/02/83053.aspx
http://gglaze.homeip.net/code_samples/msdn/function_call_benchmark/
Summary: Reflection and Performance can't be in the same sentence
(unless you negate "performance"). Eric Gunnerson:
MethodInfo.Invoke is over several orders of magnitude slower
that an interface or delegate call.
The interface or delegate calls are themselves much slower than a
non-virtual function call, but that's certainly not an option for you
either. Quoting from the function call benchmark:
Direct Call: 100.00
Interface Call: 12.51
Virtual Method: 12.33
Abstract Method: 12.32
Custom Class: 12.34
Delegate: 4.26
Event: 4.12
Multicast Delegate: 3.81
Delegate.CreateDelegate Invocation: 0.10
Type.InvokeMember: 0.06
The one solution not mentioned is using .NET 2.0's
System.Reflection.Emit.DynamicMethod, which allows you to create a
delegate instance using the System.Reflection.Emit functionality. This
would allow you to dynamically create a delegate which, when invoked,
could do a direct function call. I have no idea how well this would
perform, in comparison to the other calling mechanisms.
So, if you want to load code from external assemblies, how do you make
it fast? Don't use MethodInfo. :-)
Instead, define an abstract class or interface and require that the
custom code implement that class/interface. This will give you a
performance penalty vs. a direct function call, but direct function
calls and polymorphism don't mix, so you'd have to do the virtual method
dispatch anyway.
If you can't require that the other assemblies implement your
classes/interfaces, then you need to use delegates, or do your own
performance comparison for DynamicMethod.
- Jon
More information about the Mono-list
mailing list