Page 1 of 1

Virtual method overhead

Posted: Wed Sep 13, 2006 12:58 am
by Neo
How much of an overhead do the use of virtual methods actually cause?
I mean I do understand that they would be "slightly less" efficient for performance critical code but how "slight"?
Is it worth bothering about this overhead?

Re:Virtual method overhead

Posted: Wed Sep 13, 2006 1:29 am
by JoeKayzA
I can't give you numbers, but AFAIK the overhead boils down to looking up the object's vtable-pointer, offset to the method to be called, and do an indirect call. The performance impact is IIRC dominated by occuring cache misses and failing branch prediction (could be that modern processors are better in dealing with it already, I don't know exactly).

Generally I would say that you should use virtual methods whenever they are appropriate (when you really want to override them later and use dynamic binding), and avoid them whenever they are not needet. Just think - what's the alternative? You could make massive use of function pointers or manually check an object's type to call the right method ... and well, that's exactly what the compiler does when you call a virtual method, right?

Sorry if I got your question wrong or my explanation went in the wrong direction - just tell me!

cheers
Joe

Re:Virtual method overhead

Posted: Thu Sep 14, 2006 11:01 pm
by zloba
Is it worth bothering about this overhead?
That depends on your application (of which nothing is known here - exactly how "performance critical" is it?). Typically the answer is "no, it doesn't matter".

If it obviously does matter (makes a difference in real life, real time), or you just feel like it..

In my experience - i use virtual everywhere (eg. strings). I had only a few cases where it was a problem - bulk pixel processing. I didn't optimize it, because I'm lazy. Then i got a new computer, and it doesn't matter anymore. Tada, problem solved with zero lines of code.

Depends on the requirements.

Re:Virtual method overhead

Posted: Wed Sep 20, 2006 12:08 pm
by ces_mohab
But remember the advantages of virtual function call.
Having generic code. A pointer to function is passed and this function is implemented some where else ;D

Re:Virtual method overhead

Posted: Wed Sep 20, 2006 1:05 pm
by Candy
Main problem with them is that each function call itself takes more time. If you need to call trivial functions, the overhead becomes a problem.

If you don't call trivial functions, don't bother getting rid of them (except for promille-pinching optimizations - which you commonly don't get).