Inlining Virtual Functions

dsimcha dsimcha at yahoo.com
Fri Feb 27 10:35:08 PST 2009


According to the spec:

"Virtual functions are functions that are called indirectly through a function
pointer table, called a vtbl[], rather than directly. All non-static
non-private non-template member functions are virtual. This may sound
inefficient, but since the D compiler knows all of the class hierarchy when
generating code, all functions that are not overridden can be optimized to be
non-virtual. In fact, since C++ programmers tend to "when in doubt, make it
virtual", the D way of "make it virtual unless we can prove it can be made
non-virtual" results, on average, in many more direct function calls. It also
results in fewer bugs caused by not declaring a function virtual that gets
overridden."

Under what circumstances is this actually true?  As far as I can tell, there
is no way DMD could know about the whole class hierarchy when generating code,
given that in practice modules are compiled separately.  Not arguing that
methods should be made non-virtual by default, since the current behavior is
consistent with the "make it safe by default, efficient but unsafe if the
programmer asks" mentality, and one can always convert a function to
non-virtual by making it final.  However, I'm just curious under what
circumstances converting virtual functions into direct calls is actually possible.



More information about the Digitalmars-d mailing list