From a purely theoretical point of view without taking compiler optimiziation into account, fCheap()
is indeed fastest. Both fFinal()
and fVirtual()
incur the cost of an added lookup/indirection because they have to be called through the vtable. Also object size will increase because of the vtable, but that has nothing to do with final
. You pay the cost in size as soon as your class (or one of its bases) has any virtual functions at all.
Enter modern optimizers, i.e. devirtualization. The cost of increased object size won’t go away. The cost of the virtual calls might. Declaring a virtual function and immediately making it final makes it relatively easy for the compiler to proof at compile time exactly which function will be called. Bets are the fFinal()
call will be devirtualized to a normal function call[1]. If that can happen for FVirtual()
as well entirely depends on the situation at the call site.
In general virtual call overhead is small. I wouldn’t worry about it too much unless you have conrete evidence from profiling your actual code that this is a performance bottleneck.
Update
[1] How likely you are to win the bet depends on your compiler, its version and configuration. The only way to make sure is to look at the assembly generated from your actual code. I wouldn’t dare to make a general statement here. I played around a bit with recent GCC and Clang at -O3
in the Compiler Explorer. In every example I tried fFinal()
was inlined (granted, they were kind of trivial). So, obviously, both compilers had no problem proofing away even more than virtuality. :)