I just wondered what the real overhead of virtual function calls is and I was surprised:
Code: Select all
#include <time.h>
// performance tests for virtual functino call overheads
class Animal
{
public:
virtual void sound () = 0;
};
class Dog: public Animal
{
int ntimesbarked;
public:
void sound ();
};
void Dog::sound () { ntimesbarked ++; }
class independent_cat
{
int ntimesmeowed;
public:
void sound ();
};
void independent_cat::sound () { ntimesmeowed ++; }
void main ()
{
Dog dog;
Animal& animal = dog;
independent_cat cat;
time_t t1, t2;
/* test virtual function call overhead */
time ( &t1 );
for ( int i = 0; i < 1000000000; i ++ )
{
animal.sound ();
}
time ( &t2 );
printf ( "\n*********time to bark: %d\n", t2 - t1 );
time ( &t1 );
for ( i = 0; i < 1000000000; i ++ )
{
cat.sound ();
}
time ( &t2 );
printf ( "\n*********time to meow: %d\n", t2 - t1 );
getchar();
}
unoptimized code - ratio is 4 (virtual function call) : 3 (direct call)
optimized code - ratio is 6 (virtual function call) : 4 (direct call)
So, bottomline, a direct function call invocation is 20-25% faster. That it would be faster is not a surprise, but I never thought it would amount to so much time.
Whats the meaning: Yes, OO and interfaces are cool and that, but I'd probably avoid using inheritance and virtuality for small, atomar objects. Better make some concessions and put several behaviours into one object than to pay for the abstract beauty of a design.
Notice that this is by no means an absolut rule. Whenever I can afford a good OO design, I do it.