C# › Attributes & Reflection
Why is reflection generally slower than direct code, and what techniques (like caching or compiled expressions) mitigate this cost?
AdvancedAnswer
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 repeatedlyReal-world example Optimizing a high-throughput object mapper or serializer that would otherwise be dominated by repeated raw reflection calls.