我想知道,如果我们有以下类(class):
class MyClass
{
public:
MyClass(...)
type nonstatic_func1(...);
type nonstatic_func2(...);
...
type nonstatic_func10(...);
private:
type var1;
type var2;
...
type var10;
};
将 MyClass
的每个实例有自己的一组十个函数(即对于每个实例,是否会创建十个函数中每一个的“版本”)?与拥有 2 个函数(非静态)相比,类定义中有 20 个函数对性能有多大影响,尤其是在实例化方面,而且在使用这些实例时?变量的数量对性能有多大影响? (见下一段,vector
部分)
我问的原因是我正在编写一个程序来实例化一个类的很多实例(举例来说,我有一个相当大的 vector ,即 vector<MyClass> vec
),并且程序运行速度较慢超出我的预期。
简而言之,我想知道在实例化和使用具有大量非静态函数/变量的类的实例时有多少开销。
编辑
我对大型类实例 vector 所做的其中一件事是排序……我怀疑这是消耗性能的主要事情,因为有很多移动(以及显式和隐式复制)元素(实例) vector 周围和 vector 之间。显然,如果必须大量移动和复制的数据 block 非常大,可能会耗尽性能。
最佳答案
Will each instance of MyClass have its own set of ten functions
没有。
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?
拥有大量成员变量的主要影响是每个实例占用大量内存空间。体积大的后果是复制时会花费很多时间。不太明显的时间开销是在 CPU 缓存中。
但这些开销可能不是您出现问题的原因。
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
不要怀疑。措施。要追踪性能的去向,找出瓶颈所在。
关于C++ 非静态成员函数开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31197183/