如何在C ++中编写缓存友好的多态代码? [英] How to write cache friendly polymorphic code in C++?
问题描述
我正在写一段对性能要求很高的代码,我需要以多态方式处理大量的对象。让我们假设我有一个A类和一个从A派生的B类。我现在可以创建一个B的向量:
I am writing a piece of code with high demands on performance where I need to handle a large number of objects in a polymorphic way. Let's say I have a class A and a class B which is derived from A. I could now create a vector of B:s like this
vector<A*> a(n);
for(int i = 0; i < n; i++)
a[i] = new B();
但是如果n很大(在我的例子中为10 ^ 6或更高的顺序)非常多的调用新的,而且n个对象可能会扩散到我的主存储器,导致非常差的缓存性能。什么是正确的方法来处理这种情况?我想要做一些类似下面的事情,让所有的对象在一个连续的内存区域。
but if n is large (in the order 10^6 or more in my case) this would require very many calls to new and moreover the n objects could potentially be spread out all over my main memory resulting in very poor cache performance. What would be the right way to deal with this situation? I am thinking of doing something like the following to have all the objects in a contiguous memory region.
B* b = new B[n];
vector<A*> a(n);
for(int i = 0; i < n; i++)
a[i] = b + i;
但是一个问题是如果b不是,则如何释放新B [n]可用了(但我们还有一个)。我刚刚了解到尝试
but one problem is how to free up the memory allocated by new B[n] if b is not available anymore (but we still have a). I have just learnt that trying
delete[] a[0];
不是好主意...
推荐答案
您可以使用placement new在特定内存位置构建对象:
You can use placement new to construct an object at a particular memory location:
vector<A*> a(n);
for(int i = 0; i < n; i++)
a[i] = new(storage + i*object_size) B();
// and invoke the destructor manually to release the object (assuming A has a virtual destructor!)
a[i]->~A();
但是你不能解决真正的问题而不放弃连续存储:如果一个对象被释放,它将导致堆中的一个洞,从而导致随着时间的高碎片。您只能跟踪释放的对象并重新使用存储。
But you cannot solve the 'real' problem without giving up the continuous storage: if one object is freed, it will cause a hole in the heap, thus causing high fragmentation over time. You could only keep track of the freed objects and re-use the storage.
这篇关于如何在C ++中编写缓存友好的多态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!