Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead of creating a new class

If I have a class defined as such:

class classWithInt { public:     classWithInt(); ... private:     int someInt; ... } 

and that someInt is the one and only one member variable in classWithInt, how much slower would it be to declare a new instance of this class than to just declare a new integer?

What about when you have, say 10 such integers in the class? 100?

like image 792
wrongusername Avatar asked Dec 04 '10 06:12

wrongusername


1 Answers

With a compiler not written by drunk college students in the wee hours of the morning, the overhead is zero. At least until you start putting in virtual functions; then you must pay the cost for the virtual dispatch mechanism. Or if you have no data in the class, in which case the class is still required to take up some space (which in turn is because every object must have a unique address in memory).

Functions are not part of the data layout of the object. They are only a part of the mental concept of the object. The function is translated into code that takes an instance of the object as an additional parameter, and calls to the member function are correspondingly translated to pass the object.

The number of data members doesn't matter. Compare apples to apples; if you have a class with 10 ints in it, then it takes up the same space that 10 ints would.

Allocating things on the stack is effectively free, no matter what they are. The compiler adds up the size of all the local variables and adjusts the stack pointer all at once to make space for them. Allocating space in memory costs, but the cost will probably depend more on the number of allocations than the amount of space allocated.

like image 73
Karl Knechtel Avatar answered Sep 19 '22 23:09

Karl Knechtel