Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Thought it was worth showing how all potential options looked and their performance characteristics. Given the following helper classes and functions:</p> <pre><code>public void Test(Func&lt;int&gt; func) { var watch = new Stopwatch(); watch.Start(); for (var i = 0; i &lt;= 1000000; i++) { var test = func(); } Console.WriteLine(watch.ElapsedMilliseconds); } public class FooClass { public int Execute() { return 1;}} </code></pre> <p>Set up and execution:</p> <pre><code>using (Microsoft.CSharp.CSharpCodeProvider foo = new Microsoft.CSharp.CSharpCodeProvider()) { var res = foo.CompileAssemblyFromSource( new System.CodeDom.Compiler.CompilerParameters() { GenerateInMemory = true }, "public class FooClass { public int Execute() { return 1;}}" ); var real = new FooClass(); Test(() =&gt; real.Execute()); // benchmark, direct call var type = res.CompiledAssembly.GetType("FooClass"); var obj = Activator.CreateInstance(type); var method = type.GetMethod("Execute"); var input = new object[] { }; Test(() =&gt; (int)method.Invoke(obj, input)); // reflection invoke dynamic dyn = Activator.CreateInstance(type); Test(() =&gt; dyn.Execute()); // dynamic object invoke var action = (Func&lt;int&gt;)Delegate.CreateDelegate(typeof(Func&lt;int&gt;), null, method); Test(() =&gt; action()); // delegate } </code></pre> <p>The results are:</p> <pre><code>8 // direct 771 // reflection invoke 41 // dynamic object invoke 7 // delegate </code></pre> <p>So in those cases where you can't use delegates (if you don't know enough?), you can try <code>dynamic</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload