by CyberRabbi · 3y ago · 0 comments
The compiler is able to do that with count_inheritance() as well if it's able to prove which instance of iter_base is used in the call. I suppose even many experienced C++ developers are not aware of this. This optimization is known as "devirtualization" and is fairly well-implemented in Clang and GCC. It's even more effective since the advent of LTO. Some more info: https://quuxplusone.github.io/blog/2021/02/15/devirtualizati... https://blog.llvm.org/2017/03/devirtualization-in-llvm-and-c...
Worse, once the devirtualization optimization has failed, any further optimizations you would get from inlining the call will also fail.
If you're programming in C++, you probably do care about this level of performance, and in that case, it's nice to program in a style that guarantees it instead of hoping for a sufficiently smart compiler.
main() {
int x = foo() + 3;
}
int foo() {
return 5;
}
Without inlining you have both the overhead of the call and the arithmetic addition. If you can inline the call then you get: main() {
int x = 5 + 3;
}
But more importantly, the optimizer can now also eliminate the addition too: main() {
int x = 8;
}
This is obviously a trivial example, but in real-world code, the optimization options opened up after inlining are important.Neither implementation guarantees any particular sequence of assembly instructions. Both require hoping that a sufficiently smart compiler will compile it to a sufficiently optimal sequence of instructions.
In practice, non-virtual function calls are reliably compiled to fairly efficient code while virtual calls are much less reliable.
Like I said, this echoes the conventional wisdom that most C++ developers seem to retain. The compiler landscape has changed since that wisdom was formed, since the advent of LTO and devirtualization optimizations.