Cost of virtual function


Speed currently is about 20ns but was an order of magnitude different a few years ago. Things change!


Doing some googling on the subject you can find older pieces that specify that virtual functions as very in-efficent (circa 1995) mainly due to the compiler having to throw out the instruction cache and restart each time. This however becomes less evident using a super scalar architecture and really we are then left with whether the instructions are in the code cache or not, which is probably at worst in L3 cache unless your code is large.


And if you want to read a LOT about optimisations.


Virtual functions aren’t the bottleneck they once were, but as still not as fast as direct function calls. Really depends in what problem domain you are working. <100us, use a virtual function.  <10us you have to be a bit more careful. But a better design will always trump everything.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.