What is the performance overhead of a virtual function call?
Last updated
Direct cost: load the object's hidden vtable pointer, load the function address from the vtable, then make an indirect call. That is a couple of extra loads and an indirect branch.
The bigger cost is lost optimization: virtual calls usually can't be inlined. They can also cause branch mispredictions and cache misses.
It matters only in hot loops calling tiny functions. There, rely on devirtualization or use templates/CRTP for static polymorphism.