Reputation: 11
I do have a question related to slow performance of allocating memory for several structs. I have a struct which is looking like: see below
typedef struct _node
{
// Pointer to leaves & neigbours
struct _node *children[nrChild], *neighb[nrNeigh];
// Pointer to parent Node
struct _node *parentNode;
struct _edgeCorner *edgePointID[nrOfEdge];
int indexID; // Value
double f[latDir]; // Lattice Velos
double rho; // Density
double Umag; // Mag. velocity
int depth; // Depth of octree element
} node
At the beginning of my code I do have to create a lot of them (100.000 – 1.000.000 ) by Using :
tree = new node();
and initiating the elements after it. Unfortunately, this is pretty slow, therefore do anyone of you have an idea to improve the performance?
Upvotes: 1
Views: 463
Reputation: 146930
Firstly, you'll want to fix it so that it's actually written in C++.
struct node
{
// Pointer to leaves & neigbours
std::array<std::unique_ptr<node>, nrChild> children;
std::array<node*, nrNeigh> neighb;
// Pointer to parent Node
node* parentNode;
std::array<_edgeCorner*, nrOfEdge> edgePointID;
int indexID; // Value
std::array<double, latDir> f; // Lattice Velos
double rho; // Density
double Umag; // Mag. velocity
int depth; // Depth of octree element
};
Secondly, in order to improve your performance, you will require a custom allocator. Boost.Pool would be a fine choice- it's a pre-existing solution that is explicitly designed for repeated allocations of the same size, in this case, sizeof(node). There are other schemes like memory arena that can be even faster, depending on your deallocation needs.
Upvotes: 3
Reputation: 77304
If you know how many nodes you will have, you could allocate them all in one go:
node* Nodes = new node[1000000];
You will need to set the values afterwards, just like you would do if you did it one by one. If it's a lot faster this way, you could try an architecture where you find out how many nodes you will need before allocating them, even if you don't have that number right now.
Upvotes: 1