关于性能和速度

About performance and speed

本文关键字:速度 性能 于性能      更新时间:2023-10-16

我有一个类(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;

有三件事需要考虑-

  1. 您是说您的类A由多个线程访问。您的示例代码看起来不错,但如果这只是您为了提问而模拟的一些伪代码,那么您需要确保您的类是线程安全的。在您的情况下,您只读取值,但如果多个线程同时进行读/写操作,请确保使用一些线程同步对象来同步它们。

  2. 现在谈谈速度和性能。你的示例类似乎做得不多。我认为没有必要写课。内联函数可能也是最好的(考虑到这不是一些模拟代码)。即使您使用继承,只要您不使用虚拟函数,也不会对您造成伤害,因为在虚拟函数中查找vtable和尊重指针会有额外的开销,如果您真的关心那么多细节的话。

  3. 如果类B只是一个实现细节,那么我不会将其作为参数传递给构造函数。