Here is a code piece from MiscUtil library (by Jon Skeet & Marc Gravell):
static T Add<T>(T a, T b) {
//TODO: re-use delegate!
// declare the parameters
ParameterExpression paramA = Expression.Parameter(typeof(T), "a"),
paramB = Expression.Parameter(typeof(T), "b");
// add the parameters together
BinaryExpression body = Expression.Add(paramA, paramB);
// compile it
Func<T, T, T> add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
// call it
return add(a,b);
}
It says below the code that:
Isn't this expensive?
Well, compiling the operators isn't trivial, but the static constructor ensures that we only do this once for each signature.
What is the reason behind Func<T, T, T>
doesn't get compiled every time Add<T>(T a, T b)
method is called, but insted only gets compiled once?