Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class member function vs function with respect to speed [duplicate]

Tags:

c++

Possible Duplicate:
Virtual Functions and Performance C++

Is this correct, that class member function takes more time than a simple function? What if inheritance and virtual functions are used?

I have tried to collect my functions into a simple interface class (only member functions, no data members), and it appears that I lose time. Is there a way to fix it?

P.S. I'm checking with gcc and icc compilers and using -O3 option.

like image 520
klm123 Avatar asked Dec 12 '11 12:12

klm123


4 Answers

Premature optimization is the root of all evil

A nonstatic member function takes an additional argument, which is the object (a pointer or reference to it) on which the function is called. This is one overhead. If the function is virtual, then there is also one small indirection in case of a polymorphic call, that is, addition of the function index to the virtual table base offset. Both of these "overheads" are sooo negligable, you shouldn't worry about it unless the profiler says this is your bottleneck. Which it most likely is not.

Premature optimization is the root of all evil

like image 67
Armen Tsirunyan Avatar answered Nov 15 '22 08:11

Armen Tsirunyan


Member functions, if they're not virtual, are same as free functions. There is no overhead in its invocation.

However, in case of virtual member functions, there is overhead, as it involves indirection, and even then, it is slower when you call the virtual function through pointer or reference (that is called polymorphic call). Otherwise, there is no difference if the call is not polymorphic.

like image 27
Nawaz Avatar answered Nov 15 '22 06:11

Nawaz


There is no additional time penalty involved for member functions. Virtual functions are slightly slower but not by much. Unless you're running an incredibly tight loop, even virtual function overhead is negligible.

like image 39
Puppy Avatar answered Nov 15 '22 07:11

Puppy


For normal functions it's enough with a "jump" to them, which is very fast. The same goes for normal member functions. Virtual functions on the other hand, the address to jump to has to be fetched from a table, which of course involves more machine code instructions and therefore will be slower. However, the difference is negligible and will hardly even be measurable.

In other words, don't worry about it. If you have slowdowns, then it's most likely (like 99,999%) something else. Use a profiler to find out where.

like image 23
Some programmer dude Avatar answered Nov 15 '22 08:11

Some programmer dude