Hello,
I am writing some code which is time critical and I've noticed that memory allocation takes up a lot of time because I have to create an object up to 1,000,000 times. Each object is created individually throughout the course of the program. The objects don't need to be deleted before the end of the program. The objects contain several maps and vectors that hold pointers to other objects. I know rough upper limits on the number of elements in the maps and vectors.
In C one would use arrays instead of maps and vectors and the objects would be
1 2 3
|
struct A{
B* arr[50];
};
|
Then I would allocate memory for all objects in the beginning by calling
A* memA = (A*) malloc( 10000000 * sizeof(A));
and then increment the memA pointer every time I use a chunk of that memory.
How would I do something like that in C++?
For now lets ignore that we have maps and vectors in the object.
calling
A* memA = new A() [10000000];
will allocate memory for 1 million objects first (ok sort of what I want) and then call the constructor for each of them (don't want this as I want to call them throughout the algorithm - I don't actually know how many of those objects I really need)
Lets introduce the maps and vectors again. This is actually what hurts the most: allocating memory for each individual map-element or vector for each object.
What happens right now is the objects constructor gets called and I reserve memory for the vectors but can't do so for the maps as that functionality is not provided. But even reserving memory for the vectors is not good enough as this is done when the object is created (throughout the algorithm).
Ultimately what I need is allocating memory for 1 million objects at once where each object at that point gets allocated enough memory for each of it's maps and vectors without calling the object's constructor.
Note: memory is of course limited but not as critical as time.
Thanks for your help!