Does virtualizing all methods slow C++ down ? We
virtualize all methods as a matter of course since
we use groups of objects all over the place. To
illustrate this I have included the top portion of
our header files:
class GenGroup : public DataGroup
{
public:
int transferingDataNow;
public:
// constructor
GenGroup ();
GenGroup (const GenGroup & rhs);
GenGroup & operator = (const GenGroup & rhs);
// destructor
virtual ~GenGroup ();
virtual GenGroup * clone () { return new GenGroup ( * this); }
virtual void makeUnitsInput (InputCollection * anInpCol);
virtual void reinitStreamBox (FmFile * FMFile);
virtual DataDescriptor * descriptor (int aSymbol, int version);
...
Thanks
Lynn
To make things short,
- A polymorphic class in C++ is a class with at least one virtual
member function or one virtual base class.
- The memory extra cost in your polymorphic instance will be about one
pointer per branch having one polymorphic base class in your
inheritance DAG.
- The speed extra cost of a virtual call will be in general less than
25% compared to a monomorphic call (as soon as you really use an
abstract class for the call), up to possibly zero cost. But there is
situation where you can slow it down significantly like if the
overridden member function is using non trivial contravariant or
covariant argument (only "this" can be contravariant in c++) and
covariant return type. Then the compiler will have to apply thunks to
adjust properly the object offset back and forth to match its input
and ouput types to the virtual member function expectation.
Since you were talking about smalltalk in this thread, it is also
possible to write a message dispatcher which is as fast as late
binding (virtual call). My experience is that direct call, virtual
call or message dispatch don't make the difference (except for
expressivity and design). The matter is that polymorphic types (if
used as such) loose their value semantic (compared to concrete types)
and thus need to be dynamically created (allocated, cloned, etc). This
is where polymorphic code slow down significantly the runtime if it is
badly design.
Regards,
Laurent.