Class member function vs speed function

Possible duplicate:
Virtual Functions and C ++ Performance

Is it right that a member function takes longer than a simple function? What if inheritance and virtual functions are used?

I tried to assemble my functions into a simple interface class (only member functions, no data elements), and it seems like I'm wasting time. Is there any way to fix this?

PS I check with the gcc and icc compilers and using the -O3 option.

+4
source share
4 answers

Premature optimization is the root of all evil

A non-static member function takes an additional argument, which is the object (pointer or reference to it) that the function is called on. This is one waybill. If the function is virtual, then in the case of a polymorphic call, there is also a little indirectness, that is, adding the index of the function to the offset of the virtual table base. Both of these "overheads" are so unjustified that you should not worry about it unless the profiler says that this is your bottleneck. Most likely, this is not so.

Premature optimization is the root of all evil

+8
source

Member functions, if they are not virtual, are the same as free functions. There is no overhead in his call.

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

+3
source

There is no additional time penalty for member functions. Virtual functions are a bit slower, but not by much. If you are not performing an incredibly tight cycle, even the overhead of a virtual function is negligible.

+1
source

For normal functions, this is enough with a “jump” to them, which is very fast. The same goes for normal member functions. On the other hand, virtual functions, the address to go to the table must be extracted from the table, which, of course, is associated with more machine code and, therefore, will be slower. However, the difference is insignificant and hardly even measurable.

In other words, do not worry about it. If you have a slowdown, then this is most likely (for example, 99.999%) something else. Use the profiler to find out where.
+1
source

Source: https://habr.com/ru/post/1385888/


All Articles