Re: Virtual function call optimization
On 9/26/11 12:51 PM, Paavo Helde wrote:
cppquester<cppquester@googlemail.com> wrote in news:d47cdff0-a16e-4bcc-
bb28-476056e6a9a5@e9g2000vby.googlegroups.com:
But as at least on some platforms late binding is used I found a
solution (for all platforms):
class B
{
public:
virtual void foo() {}
};
class D: public B
{
public:
void foo() { fooD();}
void fooD() {}
};
int main(int argc, char *argv[])
{
D* d = new D();
d->fooD();
return 0;
}
Just out of curiosity (as this gets discussed pretty often), how much did
avoiding this virtual call make your application faster? (I mean your
real application with realistic usage pattern and data, not the empty
example function here). How many percents did the slow operation go
faster?
thanks
Paavo
One spot where late binding can cost alot is that it prevents inlineing
of code. If foo was an assessor function, then this could be significant.
The key is that you must let the compiler know the static type of the
object (or make it so that it can deduce it), to eliminate the late-binding.
Using a none-virtual function connection is one way. Another way that
should work is making your call
d->D::foo();
Another method, if you are willing to upgrade to C++11, and the object
definition allows it, is to declair foo() to be final, as in
class B
{
virtual void foo() {}
};
class D: public B
{
public:
void foo() final ( ... }
}
since D::foo is final, late binding is not needed if the pointer has
static type D.