Precompile Lambda Expression Tree conversions as constants?

Posted by Nathan on Stack Overflow See other posts from Stack Overflow or by Nathan
Published on 2010-06-17T00:40:56Z Indexed on 2010/06/17 0:52 UTC
Read the original article Hit count: 330

Filed under:
|
|

It is fairly common to take an Expression tree, and convert it to some other form, such as a string representation (for example this question and this question, and I suspect Linq2Sql does something similar).

In many cases, perhaps even most cases, the Expression tree conversion will always be the same, i.e. if I have a function

public string GenerateSomeSql(Expression<Func<TResult, TProperty>> expression)

then any call with the same argument will always return the same result for example:

GenerateSomeSql(x => x.Age)  //suppose this will always return "select Age from Person"
GenerateSomeSql(x => x.Ssn)  //suppose this will always return "select Ssn from Person"

So, in essence, the function call with a particular argument is really just a constant, except time is wasted at runtime re-computing it continuously.

Assuming, for the sake of argument, that the conversion was sufficiently complex to cause a noticeable performance hit, is there any way to pre-compile the function call into an actual constant?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET