Free — no signup required

The Cost of Reflection

2 min read

Why Avoiding It Is Usually Best

Reflection is powerful, but it carries real penalties that matter in production systems.

Performance: Reflection is slow. The runtime must perform dynamic type lookups, allocate intermediate objects, and bypass the compiler optimizations that make direct code fast. A reflective field access can be 10x–100x slower than a direct struct field read. For a function called once at startup (like loading config), this is irrelevant. For a function called in a hot path (like serializing every HTTP response), it matters enormously — which is why high-performance serialization libraries like ffjson and easyjson use code generation instead of reflection.

Safety: You lose compile-time type checking. If you call v.MethodByName("DoThing") and the method does not exist, you get a panic at runtime — not a compiler error. This means bugs that would normally be caught before deployment instead crash production.

Readability: Reflective code is dense. A junior engineer reading v.Field(i).Interface().(string) has to understand reflection, type assertions, and interface boxing simultaneously. This raises the maintenance burden for the entire team.

Rule of Thumb: Use reflection only when the alternative is impossible — serialization libraries, ORMs, dependency injection frameworks, and test assertion libraries are legitimate use cases. Never use it to avoid writing a type switch or to save a few lines of copy-paste code. If you find yourself reaching for reflection in application business logic, that is a design smell.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free