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?
Edit It appears that there is no way to do this exactly within C# itself. The closest you can probably come within c# is the accepted answer (though of course you would want to make sure that the caching itself wasn't slower than regenerating). To actually convert to true constants, I suspect that with some work, you could use something like mono-cecil to modify the bytecodes after compilation.