C++ 中的自定义分配器有什么问题?

what's wrong with custom allocator in C++?

Bjarne Stroustrup 在他的《C++ 编程语言》一书中说:

建议:在编写自己的分配器之前三思

Bjarne通过以上建议想表达什么?如果我编写自己的分配器,会出现哪些问题?真的有问题吗?我该如何克服这些问题?

我和两位同事 Ben Zorn 和 Kathryn McKinley(现在都在 Microsoft Research)一起写了一篇关于这个的论文(Reconsidering Custom Memory Allocation, OOPSLA 2002). It won a Most Influential Paper Award -- 这是引文。

Custom memory management is often used in systems software for the purpose of decreasing the cost of allocation and tightly controlling memory footprint of software. Until 2002, it was taken for granted that application-specific memory allocators were superior to general purpose libraries. Berger, Zorn and McKinley’s paper demonstrated through a rigorous empirical study that this assumption is not well-founded, and gave insights into the reasons why general purpose allocators can outperform handcrafted ones. The paper also stands out for the quality of its empirical methodology.

原始论文实际上比引用多了一些:这是论文的摘要。所指的 Lea 分配器构成了 Linux 分配器的基础。

Programmers hoping to achieve performance improvements often use custom memory allocators. This in-depth study examines eight applications that use custom allocators. Surprisingly, for six of these applications, a state-of-the-art general-purpose allocator (the Lea allocator) performs as well as or better than the custom allocators. The two exceptions use regions, which deliver higher performance (improvements of up to 44%). Regions also reduce programmer burden and eliminate a source of memory leaks. However, we show that the inability of programmers to free individual objects within regions can lead to a substantial increase in memory consumption. Worse, this limitation precludes the use of regions for common programming idioms, reducing their usefulness.

We present a generalization of general-purpose and region-based allocators that we call reaps. Reaps are a combination of regions and heaps, providing a full range of region semantics with the addition of individual object deletion. We show that our implementation of reaps provides high performance, outperforming other allocators with region-like semantics. We then use a case study to demonstrate the space advantages and software engineering benefits of reaps in practice. Our results indicate that programmers needing fast regions should use reaps, and that most programmers considering custom allocators should instead use the Lea allocator.

我们最近进行了一项后续研究,发现对几个现代应用程序的影响几乎完全相同:自定义分配器通常 减慢 应用程序。

除了滚动您自己的自定义内存分配器通常意味着性能和 space 命中之外,它还使调试变得更加困难,并且意味着您无法驾驭通用内存分配器的改进浪潮分配器——包括系统提供的分配器和其他类似 Hoard and tcmalloc.