Compiler Optimization of virtual function calls
Asked Answered
B

1

10

Most popular example to illustrate why virtual dispatch happens at runtime is when it cannot be determined at compile time which Derived class is going to be created. For example:

Base* b = (rand() % 2 == 1 ? new Derived1() : new Derived2());

or when it depends on user input.

Suppose none of that is the case and it can be completely determined at compile time which Derived class the base pointer is referring to.

If it is known at compile time which Derived class the base class pointer points to, does the compiler optimize the virtual function call by substituting it with appropriate Derived function and not doing vtable lookup during runtime?

Boru answered 12/6, 2018 at 11:5 Comment(3)
C++ allows a compiler to perform any optimization that has no observable effects. If the compiler can prove the devirtualizing the function call will have no observable effects, the compiler is allowed, but not required, to implement this optimization.Ebonize
Check out gcc.godbolt.org. There you can disassemble binaries produced by various compilers with various settings and see if they perform that optimization or not.Cavin
As an aside, it is also possible to manually devirtualize by sorting/seperating large collections by concrete type at runtime, to avoid virtual call overhead and improve icache use for particularly tight loops over large collectionsStumper
T
13

Such optimization is called Devirtualization. At least Clang performs it, see this blog post and this post on mailing list.

Trojan answered 12/6, 2018 at 11:8 Comment(2)
GCC does it too.Amyamyas
MSVC also knows devirtualizationPasteur

© 2022 - 2024 — McMap. All rights reserved.