Reputation: 11753
My question is related to C++ class definition. I understand that if there are many member variables existing in the class. The size of the class will increase. Increasing the number of class member functions, however, will not affect its size. However, I was wondering what is the major difference between a class with more member functions and a class with less member functions. Will it be possible that invoking a class with less member functions is much faster?
Upvotes: 4
Views: 190
Reputation: 6043
A class that has fewer functions will not be more efficient than a class with more.
Function efficiency is affected by most significantly by algorithms and I/O.
Compile time however will be affected.
Upvotes: 1
Reputation: 726509
You need per-instance space to store member variables, but member functions are not part of an instance, at least not directly. There is usually a single extra pointer that is required for each additional virtual member function, but that pointer goes to vtable which is shared among all instances of a class, and therefore does not add to per-member size.
Non-virtual member functions take space only in the code memory: their space requirements are no different from free-standing functions, the only difference being the hidden parameter for passing the pointer to this
.
The first virtual function added to a class adds an extra pointer to the space required to store an instance; additional non-virtual member functions do not play into space requirements at all.
Upvotes: 4
Reputation: 8831
No, the number of member functions will have no effect on the speed of calling the function (at least with any sane implementation). Any call to a function will just be compiled down to code that sets up the function parameters and then uses the call instruction. The compiler resolves at compile-time what the address of the function is and uses that in the call instruction or, with virtual functions, looks up in a table what address to call.
Upvotes: 1
Reputation: 3744
No, the only kind of functions that make any difference at all this respect are the virtual ones, and they are significantly slower than the usual kind no matter how many you have. In all other cases the compiler knows exactly what code to run when a particular function is called, so it won't have to do any search and the number of methods wouldn't matter.
Upvotes: 2