Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Ultimately what it comes down to is that <code>Expression&lt;T&gt;</code> is not a pre compiled delegate. It's only an expression tree. Calling Compile on a <code>LambdaExpression</code> (which is what <code>Expression&lt;T&gt;</code> actually is) generates IL code at runtime and creates something akin to a <code>DynamicMethod</code> for it.</p> <p>If you just use a <code>Func&lt;T&gt;</code> in code, it pre compiles it just like any other delegate reference.</p> <p>So there are 2 sources of slowness here:</p> <ol> <li><p>The initial compilation time to compile <code>Expression&lt;T&gt;</code> into a delegate. This is huge. If you're doing this for every invocation - definitely don't (but this isn't the case, since you're using your Stopwatch after you call compile.</p></li> <li><p>It's a <code>DynamicMethod</code> basically after you call Compile. <code>DynamicMethod</code>s (even strongly typed delegates for ones) ARE in fact slower to execute than direct calls. <code>Func&lt;T&gt;</code>s resolved at compile time are direct calls. There's performance comparisons out there between dynamically emitted IL and compile time emitted IL. Random URL: <a href="http://www.codeproject.com/KB/cs/dynamicmethoddelegates.aspx?msg=1160046" rel="nofollow">http://www.codeproject.com/KB/cs/dynamicmethoddelegates.aspx?msg=1160046</a></p></li> </ol> <p>...Also, in your stopwatch test for the <code>Expression&lt;T&gt;</code>, you should start your timer when i = 1, not 0... I believe your compiled Lambda will not be JIT compiled until the first invocation, so there will be a performance hit for that first call.</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