简体   繁体   中英

C++ Non-static member functions overhead

I would like to know that, if we have the following class:

class MyClass  
{
public:
  MyClass(...)  
  type nonstatic_func1(...);
  type nonstatic_func2(...);
  ...
  type nonstatic_func10(...);
private:
  type var1;
  type var2;
  ...
  type var10;
};

Will each instance of MyClass have its own set of ten functions (ie for each instance, will a "version" of each of the ten functions be created)? How much will having, say, 20 functions in a class definition impact performance, as opposed to having, say, 2 functions (non-static), especially regarding instantiation, but also in working with these instances? How much will the amount of variables affect the performance? (see the next paragraph, the vector part)

The reason I am asking is I am writing a program that is instantiating a lot of instances of a class (to illustrate, I have quite a large vector, ie vector<MyClass> vec , for example), and the program is running slower than I anticipated.

In a nutshell, I'd like to know how much overhead there is in instantiating, and working with, an instance of a class that has a lot of non-static functions/variables.

EDIT

One of the things I do with my large vector of class instances is sorting...this is the main thing I suspect is draining performance, since there's a lot of moving (and copying, explicitly and implicitly) elements (instances) around and between vectors. Obviously if the chunk of data that has to be moved and copied so much is quite large, it could drain performance.

Will each instance of MyClass have its own set of ten functions

No.

How much will having, say, 20 functions in a class definition impact performance, as opposed to having, say, 2 functions (non-static), especially regarding instantiation, but also in working with these instances?

Therefore, no.

How much will the amount of variables affect the performance?

The major impact of having a lot of member variable is that each instance occupies a lot of memory space. The consequence of being big in size is it would spend a lot of time when it is copied. A less obvious time overhead would be in CPU caching.

But these overhead may not be the causes of your problem.

One of the things I do with my large vector of class instances is sorting...this is the main thing I suspect is draining performance

Don't suspect. Measure. To track down where the performance goes, find out where the bottleneck is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM