用一个 'new' 分配四个对象数组
allocating four object arrays with one 'new'
我有一个 class 有四个这样的动态数组:
CObjA * objAArray;
CObjB * objBArray;
CObjC * objCArray;
CObjD * objDArray;
我这样初始化它们:
objAArray = new CObjA[numObj];
objBArray = new CObjB[numObj];
objCArray = new CObjC[numObj];
objDArray = new CObjD[numObj];
问题是这四个内存分配需要很长时间 - 如果我必须像这样创建 40'000 个对象,性能会非常糟糕。
我的问题是:有没有办法通过一次 new
操作分配所有四个数组?
如果我创建一个新结构:
struct _arrays
{
CObjA objA;
CObjB objB;
CObjC objC;
CObjD objD;
};
并改用该结构的一个数组,我只需要使用一个 new
:
_arrays * arr = new _arrays[numObj];
但是对象在内存中的布局不正确。然后它们在内存中为 CObjA1-CObjB1-CObjC1-CObjD1-CObjA2-CObjB2...
。而不是首先所有 CObjA
个对象,然后所有 CObjB
个对象,...
有没有办法使用一个 new
但仍能获得正确的对象内存布局?
您可以通过 malloc 使用单个分配来实现您需要的功能,然后使用 "placement new" 语法在所需的内存位置创建对象。
正如@RSahu 在他对您的问题的评论中提到的,如果导致性能瓶颈的不是对象的构造,而是原始内存分配本身,我会感到惊讶。也就是说,一种方法是分配一个 char *
类型的数组,然后将内存位置分配给您的数组,如下所示:
char* allocations = new char[numObj * (sizeof(CObjA) + sizeof(CObjB) +
sizeof(CObjC) + sizeof(CObjD))];
CObjA * objAArray = reinterpret_cast<CObjA *>(allocations);
CObjB * objBArray = reinterpret_cast<CObjB *>(allocations + numObj * sizeof(CObjA));
CObjC * objCArray = reinterpret_cast<CObjC *>(allocations + numObj * (sizeof(CObjA)
+ sizeof(CObjB));
CObjD * objDArray = reinterpret_cast<CObjD *>(allocations + numObj * (sizeof(CObjA)
+ sizeof(CObjB)
+ sizeof(CObjC));
... //use arrays here
delete [] allocations; //deletes all allocations in one go
我有一个 class 有四个这样的动态数组:
CObjA * objAArray;
CObjB * objBArray;
CObjC * objCArray;
CObjD * objDArray;
我这样初始化它们:
objAArray = new CObjA[numObj];
objBArray = new CObjB[numObj];
objCArray = new CObjC[numObj];
objDArray = new CObjD[numObj];
问题是这四个内存分配需要很长时间 - 如果我必须像这样创建 40'000 个对象,性能会非常糟糕。
我的问题是:有没有办法通过一次 new
操作分配所有四个数组?
如果我创建一个新结构:
struct _arrays
{
CObjA objA;
CObjB objB;
CObjC objC;
CObjD objD;
};
并改用该结构的一个数组,我只需要使用一个 new
:
_arrays * arr = new _arrays[numObj];
但是对象在内存中的布局不正确。然后它们在内存中为 CObjA1-CObjB1-CObjC1-CObjD1-CObjA2-CObjB2...
。而不是首先所有 CObjA
个对象,然后所有 CObjB
个对象,...
有没有办法使用一个 new
但仍能获得正确的对象内存布局?
您可以通过 malloc 使用单个分配来实现您需要的功能,然后使用 "placement new" 语法在所需的内存位置创建对象。
正如@RSahu 在他对您的问题的评论中提到的,如果导致性能瓶颈的不是对象的构造,而是原始内存分配本身,我会感到惊讶。也就是说,一种方法是分配一个 char *
类型的数组,然后将内存位置分配给您的数组,如下所示:
char* allocations = new char[numObj * (sizeof(CObjA) + sizeof(CObjB) +
sizeof(CObjC) + sizeof(CObjD))];
CObjA * objAArray = reinterpret_cast<CObjA *>(allocations);
CObjB * objBArray = reinterpret_cast<CObjB *>(allocations + numObj * sizeof(CObjA));
CObjC * objCArray = reinterpret_cast<CObjC *>(allocations + numObj * (sizeof(CObjA)
+ sizeof(CObjB));
CObjD * objDArray = reinterpret_cast<CObjD *>(allocations + numObj * (sizeof(CObjA)
+ sizeof(CObjB)
+ sizeof(CObjC));
... //use arrays here
delete [] allocations; //deletes all allocations in one go