r/cpp • u/david-alvarez-rosa • Apr 23 '26
Devirtualization and Static Polymorphism
https://david.alvarezrosa.com/posts/devirtualization-and-static-polymorphism/
81
Upvotes
r/cpp • u/david-alvarez-rosa • Apr 23 '26
View all comments
2
u/david-alvarez-rosa Apr 23 '26
Ever wondered why your “clean” polymorphic design underperforms in benchmarks? Virtual dispatch enables polymorphism, but it comes with hidden overhead: pointer indirection, larger object layouts, and fewer inlining opportunities.
Compilers do their best to devirtualize these calls, but it isn’t always possible. On latency-sensitive paths, it’s beneficial to manually replace dynamic dispatch with static polymorphism, so calls are resolved at compile time and the abstraction has effectively zero runtime cost.