let me have a testing question as Iam not sure how to measure it correctly.
The question basically is:
Which is faster ?
A. Call 1000 times a virtual function OR
B. call 1000 times a normal function trough a function pointer.
For example:
A.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Base
{
public: virtualvoid myfunc() = 0;
};
class Child: public Base
{
public: void myfunc(){...}; //overriding the base class function
}
int main()
{
Child myclass;
call myclass.myfunc() 1000 times
}
B.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class SomeClass
{
public: void myfunc(){ ... }
};
int main()
{
SomeClass myclass;
void (*foo)();
foo = &myclass.myfunc;
call foo() 1000 times
}
What do You guys think which one would perform better ?
Assume that the compiler will surely not be able decide the class type in the virtual function case (A). And also the functions are quite complex and big.
Why do you want to know that? Difference will be negligible assuming the functions are "quite complex and big".
Anyway, virtual call is almost always two dereferences and a call. On the other hand, calling a method through a pointer to member function is much more "unstandardized". I would guess it is a single check (whether the function is virtual), and then a call (as the function is not virtual).
@Avithohol
It means that their implementation varies greatly between compilers, unlike virtual calls which are almost always implemented in the same way.
Thank You guys, to give you more insight, i can extend the question:
This function will be called in an "infinite" loop
(traditional event driven program with message pump)
and it will contain lot of OpenGL drawing, complex calculations (A.I., physics etc.)
It will be the core for a simple game engine,
so iam just wondering whether i should stick with the function pointer (like a lot of drawing framework do) or i can move on to OOP world and use virtual function overriding.
if I were you, I'd be more concerned about how to "free my CPU" when the function isn't doing anything useful, and I'd pay attention to how it is woken back up (thread context switches, etc...)
while the core is running, I'd take care to minimize allocating memory or doing other costly operations which may cause lag