Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is Func<> created from Expression<Func<>> slower than Func<> declared directly?
    primarykey
    data
    text
    <p>Why is a <code>Func&lt;&gt;</code> created from an <code>Expression&lt;Func&lt;&gt;&gt;</code> via .Compile() considerably slower than just using a <code>Func&lt;&gt;</code> declared directly ?</p> <p>I just changed from using a <code>Func&lt;IInterface, object&gt;</code> declared directly to one created from an <code>Expression&lt;Func&lt;IInterface, object&gt;&gt;</code> in an app i am working on and i noticed that the performance went down.</p> <p>I have just done a little test, and the <code>Func&lt;&gt;</code> created from an Expression takes "almost" double the time of an <code>Func&lt;&gt;</code> declared directly.</p> <p>On my machine the Direct <code>Func&lt;&gt;</code> takes about 7.5 seconds and the <code>Expression&lt;Func&lt;&gt;&gt;</code> takes about 12.6 seconds.</p> <p>Here is the test code I used (running Net 4.0)</p> <pre><code>// Direct Func&lt;int, Foo&gt; test1 = x =&gt; new Foo(x * 2); int counter1 = 0; Stopwatch s1 = new Stopwatch(); s1.Start(); for (int i = 0; i &lt; 300000000; i++) { counter1 += test1(i).Value; } s1.Stop(); var result1 = s1.Elapsed; // Expression . Compile() Expression&lt;Func&lt;int, Foo&gt;&gt; expression = x =&gt; new Foo(x * 2); Func&lt;int, Foo&gt; test2 = expression.Compile(); int counter2 = 0; Stopwatch s2 = new Stopwatch(); s2.Start(); for (int i = 0; i &lt; 300000000; i++) { counter2 += test2(i).Value; } s2.Stop(); var result2 = s2.Elapsed; public class Foo { public Foo(int i) { Value = i; } public int Value { get; set; } } </code></pre> <h2>How can i get the performance back ?</h2> <p>Is there anything i can do to get the <code>Func&lt;&gt;</code> created from the <code>Expression&lt;Func&lt;&gt;&gt;</code> to perform like one declared directly ?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    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