Advertisement

virtual functions

Started by February 11, 2000 05:34 PM
2 comments, last by LeeIsMe 25 years, 1 month ago
Somewhere on this message board I heard that virtual functions are a lot slower than regular functions. If this is true, then how else should I use classes that will be overloaded and returned in dlls.
I think you may be overestimating the performance penalty of virtual functions. They ARE slower than normal functions, but not so much so as to make them unusable. Essentially, calling a virtual function requires one extra pointer dereference operation, and then proceeds like a normal function call. And since there is no real way to duplicate their functionality, you''re better off using them (and gaining the benefits of good design) than not. (I''m not saying that virutal functions are flat out a sign of good design, but if you can use them to create a better structured, OO design, then by all means do so.)

-Brian
Advertisement
Virtual functions require the compiler to build a table of pointers indexed by class name for your hierarchy of classes. When a traditional function is compiled it becomes a segment of code that can be referenced in other segments by way of a pointer. Since these pointers, when compiled, are static, the only way for a virtual function call to work is for the executable to determine which function pointer to use at runtime. In this regard virtual functions are slower because the call to a one requires a translation operation to get the correct function pointer. The translation operation becomes more expensive with larger numbers of overloaded functions. This is because the executable has to track more virtual function pointers, hence increasing the number of operations needed to search the list for the right pointer. I hope this helps explain why they are slower. When used right the cost of virtual functions should go unnoticed but overdoing it with virtual functions(ie polymorphism) has its performance costs. This should help you to be able to figure them out.

Kressilac
Derek Licciardi (Kressilac)Elysian Productions Inc.
Thanks a lot for your detailed replies.

This topic is closed to new replies.

Advertisement