17.7 Performance: Generics vs Trait Objects Trade-offs
Alright, let’s cut through the noise. You’ve got generics, and you’ve got trait objects (dyn Trait). Both let you write flexible code, but they pay for that flexibility in very different currencies. One uses compile-time bucks, the other uses runtime cash. Picking the right one isn’t about which is “better”—it’s about which debt you want to owe. The Core of the Conflict: Monomorphization vs. Dynamic Dispatch The entire trade-off boils down to one compiler concept: monomorphization. It’s a ten-dollar word for a simple, brutally effective process. When you write a generic function, the compiler doesn’t just leave it as is. It looks at every concrete type you actually use that generic with and stamps out a bespoke, hardcoded version of the function for each one.