r/cpp • • Apr 23 '26

Devirtualization and Static Polymorphism

https://david.alvarezrosa.com/posts/devirtualization-and-static-polymorphism/
81 Upvotes

36 comments sorted by

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 virtual is 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