Back to results for “Generics”
C# › Attributes & Reflection

Why is reflection generally slower than direct code, and what techniques (like caching or compiled expressions) mitigate this cost?

Advanced

Answer

Reflection involves runtime metadata lookups, dynamic type resolution, and boxing/unboxing for value types on every call — significantly slower than direct, JIT-optimized code. Mitigation techniques include caching PropertyInfo/MethodInfo lookups (avoiding repeated GetProperty() calls), or compiling a reflection-based operation into a cached, reusable delegate via System.Linq.Expressions for near-native performance after the first call.
// Slow: repeated reflection lookup every call
void SetNameSlow(object obj, string name) {
  obj.GetType().GetProperty("Name")!.SetValue(obj, name);
}

// Fast: compile once, reuse the delegate many times
var param = Expression.Parameter(typeof(User));
var prop = Expression.Property(param, "Name");
// ... build and compile an Expression<Action<User, string>> once, cache it, invoke repeatedly
Real-world example Optimizing a high-throughput object mapper or serializer that would otherwise be dominated by repeated raw reflection calls.

Common follow-ups: At roughly what call-volume threshold does the compiled-expression approach's upfront cost start paying off over raw reflection?