C++ 中的 malloc 以提高性能

malloc in C++ for performance

我正在优化以性能为优先的程序的计算密集型部分。

目前我正在使用std::array用于无法立即初始化的各种类型的数据和缓存。为了性能,我想为缓存 分配内存而不默认初始化元素 ,这样我就可以在计算它们后用适当的值初始化它们。我能想到的唯一方法是使用 malloc。是否有任何“更干净”的方法来完成此操作,这是在 C++ 中合理使用 malloc 吗?

我知道“永远不要使用 malloc/new[]”的常见建议。显然需要基于测量进行优化。这不是过早的优化。这部分代码在每个线程上每秒调用约 250 万次,每次调用应 运行 在 1000 纳秒内。

分配一个字节数组,该数组的大小足以容纳您最终要构造的最大元素数。然后,只要您想在数组中的给定字节偏移处构造对象,就可以使用 placement-new

您也可以使用 std::aligned_storage 作为数组元素类型,而不是使用原始字节。链接的文档甚至提供了这种确切技术的示例。

这里是如何在不初始化 std::array 并且不求助于 C 风格 API 或像 aligned_storage.

这样的低级 API 的情况下干净地分配 std::array
#include <memory>
#include <array>

template <class T> struct uninit : public T
{
    uninit() {} // do not omit, do not make = default.
};

using myarray = std::array<int, 1337>;
using myarray_uninit = uninit<myarray>;

std::unique_ptr<myarray> allocate_myarray()
{
    return std::make_unique<myarray_uninit>();
}

Live demo

这个特定的答案与在堆上分配东西的性能与在堆上分配东西的性能无关。