HeadlinesBriefing favicon HeadlinesBriefing.com

Virtual Dispatch vs Static Polymorphism: Performance Trade-offs

Hacker News •
×

Virtual dispatch enables runtime polymorphism but introduces hidden overhead through pointer indirection and reduced inlining opportunities. Compilers attempt to devirtualize these calls when possible, but manual optimization often yields better results. The performance impact becomes significant on latency-sensitive paths where every cycle counts.

At the assembly level, virtual calls require loading a vtable pointer and performing indirect calls, which prevents inlining and increases branch mispredictions. Compiler flags like -fwhole-program and -flto help by enabling cross-translation unit optimizations, while the `final` keyword provides method-specific guarantees. These techniques allow the compiler to replace virtual calls with direct calls when the runtime type is known.

When devirtualization isn't possible, static polymorphism through CRTP offers a zero-cost abstraction alternative. By templating the base class on the derived class, calls are resolved at compile time without vtable overhead. C++23's deducing this feature simplifies CRTP implementation by templating only member functions rather than entire classes. The trade-off is that each instantiation becomes a distinct type, requiring templated interfaces for shared functionality across different derived types.