Cost of virtual function

Preamble

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

Information

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.

from

http://ithare.com/infographics-operation-costs-in-cpu-clock-cycles/

http://ithare.com/wp-content/uploads/part101_infographics_v06.png

And if you want to read a LOT about optimisations.

http://www.agner.org/optimize/optimizing_cpp.pdf

Conclusion

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.