1

我正在编写一个速度优化至关重要的程序。每增加 1% 的速度是好的。

在一个经常调用的函数中,我需要一个(小)类 MyClass 的固定大小的数组。一开始,我使用了一个 std::vector。整个东西很小(通常是 256 项,类大小是 12 字节,如果数组是 16 字节对齐的,这意味着 3072 字节)

现在发生了这样的事情:

  • 使用在堆栈上分配的 C 样式数组 MyClass[256] 可以提高性能。据我了解,这是因为没有进行内存分配/删除,堆栈分配是免费的。
  • 使用 ::operator new 进行内存分配也可以提高性能。因为它跳过了我不需要的类初始化。除此之外,我更喜欢尽可能避免原始内存初始化。

因此,在堆栈上分配和跳过初始化应该更快。如果需要,我可以重写类构造函数,但我不知道如何。

谢谢,

艾蒂安

4

1 回答 1

3

You don't need initialization? So presumably MyClass has no constructor, and no data members that need constructing? In that case the compiler will not do any initialization anyway. So just use new.

If MyClass does have a constructor then you should consider why it does when, as you say, you don't need initialization.

If MyClass does have data members that need constructing (a std::string say) then I'd query your assertion that you don't need initialization.

But you're right on the other point, switching from vector to an array should save you some time.

于 2013-09-24T09:57:26.707 回答