关于性能和速度
About performance and speed
我有一个类(a),用于不同的线程。只有这个类使用另一个类(B)。现在,我为类a中的类B对象继承或分配内存。但我认为如果我将类B的对象作为参数传递给a的构造函数会更好。在这种情况下,不需要在类a中不断创建或继承类B。在我看来,这会更快。
那么它在速度和性能方面会更好吗?
class B {
public: int i;
B() {
i = 123;
}
~B() {}
int get() const { return i; }
}
//first solutions
class A:public B {
public: int j;
A() {}
~A() {}
int somethingMethod(int n) {
j = get() * n;
return j;
}
}
A * a1 = new A(); //for example
cout << a1->somethingMethod(1) << endl;
cout << a1->somethingMethod(14) << endl;
A * a2 = new A();
cout << a1->somethingMethod(45) << endl;
A * a3 = new A();
cout << a1->somethingMethod(12) << endl;
cout << a1->somethingMethod(24) << endl;
cout << a1->somethingMethod(41) << endl;
A * a4 = new A(); //etc.
cout << a1->somethingMethod(41) << endl;
delete a1, a2, a3, a4;
//second solution
class A: {
public: int j;
B * b;
A(B * _b):b(_b) {}
~A() {}
int somethingMethod(int n) {
j = b->get() * n;
return j;
}
}
B * b = new B();
A * a1 = new A(b); //for example
cout << a1->somethingMethod(1) << endl;
cout << a1->somethingMethod(14) << endl;
A * a2 = new A(b);
cout << a1->somethingMethod(45) << endl;
A * a3 = new A(b);
cout << a1->somethingMethod(12) << endl;
cout << a1->somethingMethod(24) << endl;
cout << a1->somethingMethod(41) << endl;
A * a4 = new A(b); //etc.
cout << a1->somethingMethod(41) << endl;
delete b, a1, a2, a3, a4;
有三件事需要考虑-
-
您是说您的类A由多个线程访问。您的示例代码看起来不错,但如果这只是您为了提问而模拟的一些伪代码,那么您需要确保您的类是线程安全的。在您的情况下,您只读取值,但如果多个线程同时进行读/写操作,请确保使用一些线程同步对象来同步它们。
-
现在谈谈速度和性能。你的示例类似乎做得不多。我认为没有必要写课。内联函数可能也是最好的(考虑到这不是一些模拟代码)。即使您使用继承,只要您不使用虚拟函数,也不会对您造成伤害,因为在虚拟函数中查找vtable和尊重指针会有额外的开销,如果您真的关心那么多细节的话。
-
如果类B只是一个实现细节,那么我不会将其作为参数传递给构造函数。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- OpenMP阵列性能较差
- 递归列出所有目录中的C++与Python与Ruby的性能
- 为什么在读取文件大小时文件IO速度会发生变化
- 大小相等但成员数量不同的结构之间的性能差异
- 为什么constexpr的性能比正常表达式差
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 文件系统:复制功能的速度秘诀是什么
- 在类中使用随机生成器时出现性能问题
- 如何比较两个函数的速度和性能
- 查询性能计数器限制/加快幻灯片速度
- Qt程序的速度性能:Windows与Linux
- 辅助功能级别对性能或速度的影响
- 基于libpcap的应用程序是否会影响网络速度/性能
- CPP 中速度性能的测试功能
- 性能方面,按位运算符与正常模数的速度有多快
- cBlas 性能 + 速度
- Python模拟显示慢性能,如何加快数组计算速度
- SDL_HWSURFACE和SDL_SWSURFACE在速度和性能方面有什么区别吗?
- 关于性能和速度