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
Show parent comment
2
u/matthieum Apr 24 '26
Indeed.
The cost of a virtual call is not really the run-time cost. Direct or indirect calls have the same cost on x64, and as long as the v-table is in cache, it takes only a few instructions to get the function pointer.
The real cost is definitely the loss of optimization opportunities. The lack of inlining can kill here. That is, the cost of
virtualis similar to that__inline__((never))-- or close enough, const-prop is another foiled optimization.Funnily enough, I've seen pieces of code run faster by adding a
virtual, simply because this led to sweeping changes to inlining opportunities :/ sigh