Virtual method overhead

Programming, for all ages and all languages.
Post Reply
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

Virtual method overhead

Post 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?
Only Human
JoeKayzA

Re:Virtual method overhead

Post 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
zloba

Re:Virtual method overhead

Post 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.
User avatar
ces_mohab
Member
Member
Posts: 77
Joined: Wed Oct 18, 2006 3:08 am

Re:Virtual method overhead

Post 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
To write an OS you need 2 minds one for coding and other for debugging.
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:Virtual method overhead

Post 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).
Post Reply