📎 Webclip
The Performance Benefits of Final Classes
The article says final marks a class or virtual member function as one that cannot be derived from or overridden. It argues that this helps the compiler enforce design intent and can also improve performance by enabling devirtualization.
Reading notes#
finalprevents further derivation from a class or overriding of a virtual member function.- The compiler can use
finalto identify more virtual calls that can be resolved at compile time. - Virtual calls use an indirect call through the vtable, which is more expensive than a direct call because of branch prediction, instruction cache, and missed inlining opportunities.
- Devirtualization resolves virtual calls at compile time instead of runtime.
- In the example with
dog::speak, compilers inline the call intomainbecause the only possible result is known. - In the
derived final : baseexample, a call tod.f()can be inlined becausederivedcannot be further derived. - Without
final, the assembly shown uses a vtable load and an indirect jump. - The article says the compiler may optimize more aggressively when it can see the full code path that will execute.
- The conclusion recommends checking whether codebases have places where
finalcould improve performance and measuring the impact.
