Why virtual calls are harder to optimise
Question
Why do virtual function calls limit what an optimising compiler can do, and which optimisations are open for non-virtual calls?
Short answer
The target of a virtual call is unknown at compile time, so it usually cannot be inlined. That blocks the follow-on optimisations inlining enables: constant propagation, dead-code removal, loop vectorisation and register allocation across the call, plus the indirect branch can mispredict. Non-virtual calls have a fixed target and can be inlined and optimised freely; compilers may devirtualise when the dynamic type is provable (e.g. final classes).
Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.21, p.227; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solutionLessons behind this question
- Optimisation Problems
- Constrained Optimisation and Lagrange Multipliers
- Option Mechanics: Calls, Puts, Moneyness, Intrinsic Value, and Exchange vs. OTC Markets
Start with a free lesson: Options is part of a free topic. Create a free account, no card needed, to read it in full with worked solutions.
Read it free