Question

Which of the following gives better performance:

DynamicMethod dm = ....
..
//create IL for 'dm'
//store 'dm' for later use
..
..
later
..
..
dm.Invoke(..);

OR

DynamicMethod dm;
Delegate del = dm.CreateDelegate()
// store 'del' for later use
..
..
later
..
..
del(..);

Note that typically 10s or 100s of different DynamicMethods will be created and each DynamicMethod (via hashtable of stored 'dm's or 'del's) will be called multiple times.

Was it helpful?

Solution

If you are just creating 'throw away' methods (iow not using them again), it does not matter.

If you however reuse them, the second option will be significantly faster.

Update:

The first option uses reflection only (RuntimeMethodHandle.InvokeMethodFast(...)). I will assume that internally, the DynamicMethod will be compiled at some stage too, which will incur some additional overhead on the first call and possibly additional calls.

The second option, the DynamicMethod is explicitly compiled to a known delegate type. As everyone should know, 'direct' delegate calls are almost as fast as a 'direct' method call.

Opinion:

Always use the second option, even when just using them once. You will have some compile time benefits additionally to the massive performance increase.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top