Note that there are some explanatory texts on larger screens.

plurals
  1. PORun dynamically compiled C# code at native speed... how?
    primarykey
    data
    text
    <p>I have read several posts on SO about writing and compiling dynamic C# code. For example, <a href="https://stackoverflow.com/questions/3188882/compile-and-run-dynamic-code-without-generating-exe">this post</a>. I understand it can be done several ways.</p> <p>However, calling the code invoker is slow. I did a simple benchmark, and it's some 500 X slower than calling a native method.</p> <p>What I want to be able to do is the equivalent of loading a DLL and calling one of its methods directly ("natively"), which will give the speed benefits I want.</p> <p>What is the easiest way to go about this? Compile the dynamic code to a dll and then load it? Can it be done in memory?</p> <p><strong>EDIT</strong></p> <p>I don't care about compilation time. Only execution.</p> <p><strong>EDIT 2, 3</strong></p> <p>Here is the benchmark code I wrote:</p> <pre><code> public static int Execute(int i) { return i * 2; } private void button30_Click(object sender, EventArgs e) { CSharpCodeProvider foo = new CSharpCodeProvider(); var res = foo.CompileAssemblyFromSource( new System.CodeDom.Compiler.CompilerParameters() { GenerateInMemory = true, CompilerOptions = @"/optimize", }, @"public class FooClass { public static int Execute(int i) { return i * 2; }}" ); var type = res.CompiledAssembly.GetType("FooClass"); var obj = Activator.CreateInstance(type); var method = type.GetMethod("Execute"); int i = 0, t1 = Environment.TickCount, t2; //var input = new object[] { 2 }; //for (int j = 0; j &lt; 10000000; j++) //{ // input[0] = j; // var output = method.Invoke(obj, input); // i = (int)output; //} //t2 = Environment.TickCount; //MessageBox.Show((t2 - t1).ToString() + Environment.NewLine + i.ToString()); t1 = Environment.TickCount; for (int j = 0; j &lt; 100000000; j++) { i = Execute(j); } t2 = Environment.TickCount; MessageBox.Show("Native: " + (t2 - t1).ToString() + Environment.NewLine + i.ToString()); var func = (Func&lt;int, int&gt;) Delegate.CreateDelegate(typeof (Func&lt;int, int&gt;), method); t1 = Environment.TickCount; for (int j = 0; j &lt; 100000000; j++) { i = func(j); } t2 = Environment.TickCount; MessageBox.Show("Dynamic delegate: " + (t2 - t1).ToString() + Environment.NewLine + i.ToString()); Func&lt;int, int&gt; funcL = Execute; t1 = Environment.TickCount; for (int j = 0; j &lt; 100000000; j++) { i = funcL(j); } t2 = Environment.TickCount; MessageBox.Show("Delegate: " + (t2 - t1).ToString() + Environment.NewLine + i.ToString()); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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