[Solved] What is more Efficient? Implementation in overloaded function or by checking object type in Base class function


For many reasons – code maintainability, extensibility, concision, reliability, minimising the amount of code that needs to be recompiled/redistributed to pick up changes in some library code it uses – you should almost always use virtual functions rather that writing your own switching mechanisms. If you need to ask about it on stackoverflow, I’d go as far as to say always prefer virtual functions until you understand all the implications and could be answering questions like this one.

That said, you’re specifically asking what’s more efficient, so lets say the importance of that eclipses all other considerations above. Whenever you really have to care (your program’s known to be too slow with real life data/inputs on the hardware that it needs to run on), then do try plausible alternatives and measure – things can vary with compilers, hardware, operating systems etc..

Is a switch plausibly better than virtual dispatch? Yes. Switching can more efficient, but not if you’re doing it with std::strings (which are expensive to compare), and especially not if you’re having ClassName() create string temporaries (which require dynamic memory allocation each time). If you instead used an enum with enumerators for the different classes, and a switch between them, and the functions to call can be inlined or even optimised away, then in my measurements I’ve seen an order-of-magnitude speed improvement over virtual dispatch. If the functions you’re calling do a non-trivial amount of work themselves, the speed of switching to them is likely to be an insignificant overhead.

1

solved What is more Efficient? Implementation in overloaded function or by checking object type in Base class function