| ▲ | on_the_train 6 hours ago | |||||||||||||
That's the reason why polymorphism is sometimes described as slow. It's not really slow... But it prevents inlining and therefore always is a function call as opposed to sometimes no function call. It's not the polymorphism is slow. It's that alternatives can sometimes compile to zero | ||||||||||||||
| ▲ | dataflow 2 hours ago | parent | next [-] | |||||||||||||
Every 8 methods knock out at least 1 cache line for you (on x64, at least). You're probably not calling 8 adjacent methods on the same exact type either, you're probably doing something with a larger blast radius. Which means sacrificing even more of caches. And this doesn't show up in the microbenchmarks people normally write because they vtables are hot in the cache. So you're really banking on this not affecting your program. Which it doesn't, if you keep it in mind and do it sparingly. But if you start making everything virtual it should hit you vs. merely making everything noinline. | ||||||||||||||
| ▲ | branko_d 6 hours ago | parent | prev | next [-] | |||||||||||||
On the other hand, if the compiler can prove at compile-time what type the object must have at run-time, it can eliminate the dynamic dispatch and effectively re-enable inlining. | ||||||||||||||
| ||||||||||||||
| ▲ | armchairhacker 6 hours ago | parent | prev [-] | |||||||||||||
Pedantic, but I assume you're referring to virtual methods? Ad hoc polymorphism (C++ templates) and parametric polymorphism (Rust) can be inlined. Although those examples are slow to compile, because they must be specialized for each set of generic arguments. | ||||||||||||||
| ||||||||||||||