DynamicMethod.Invoke or DynamicMethod.CreateDelegate+Invoke - which is faster?

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.

Answers


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.


Need Your Help

jQuery: Date picker starts opened in dialog, only in IE

jquery jquery-ui internet-explorer-8 datepicker jquery-dialog

I have found an interesting bug when using a jQuery dialog where the first field in the dialog is a date picker. When the dialog is opened in IE the date picker for the first field automatically op...

How to start Django server that is located in another machine

django ftp webserver

For business matters i've moved my local server to enterprise's server for doing some tests but i don't know how to start/stop server via local, i guess it's launching via python runserver... but i...