csharp / expert
Snippet
Runtime Performance Optimization via Expression Trees
Expression trees allow you to define code as a data structure and compile it into executable IL (Intermediate Language) at runtime. This technique is used to create highly optimized logic dynamically, bypassing the overhead of reflection or interpretation while ensuring type safety. It is particularly useful for building high-performance mappers or math engines.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Linq.Expressions;public class FastMath{public static Func<int, int> CreateMultiplier(int factor){ParameterExpression input = Expression.Parameter(typeof(int), "n");BinaryExpression body = Expression.Multiply(input, Expression.Constant(factor));return Expression.Lambda<Func<int, int>>(body, input).Compile();}}// Usage:var doubleIt = FastMath.CreateMultiplier(2);int result = doubleIt(21); // 42
Breakdown
1
ParameterExpression input = Expression.Parameter(typeof(int), "n");
Defines a typed parameter 'n' that will be passed to the generated function.
2
return Expression.Lambda<Func<int, int>>(body, input).Compile();
Compiles the expression tree into a high-performance delegate that can be executed directly.