PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Need help optimizing this piece of code

Hi guys,

I would like to optimize this piece of code. Anyone has any ideas?

Code:
struct tgrid {
tsprite *s;
tgrid *prev;
};

__forceinline void AddGridD (tgrid *&nd, tsprite *s)
{
tgrid *n = (tgrid *)malloc(sizeof(tgrid));

n->s = s;
n->prev = nd;

nd = n;
}

// main part here

for (int y = y1; y <= y2; y++)
{
tgrid **g = (grid + (y * GRIDHEIGHT) + x1);

for (int x = x1; x <= x2; x++)
{
AddGridD(*g, s);
g++;
}
}


Could I read assign two grid cells at the time or something? Can I just assign one row of cells to a temporary variable and then copy it to the grid? I don't just stupid ideas, probably wouldn't help.
You don’t really want to be calling malloc anywhere in time critical code, rather pre allocate memory you’re going to need during startup.

If you have to have this at runtime id recommend using a custom memory manager that can basically do that for you.
The memory allocation is probably the killer here. Use an array of pre-allocated objects instead.
I will probably use the same technic I used in another part of my program where once the object (structure) is assigned I don't free it and just use a pointer to move to the next or previous object and create a new one only when neccessary. I will have to add a tgrid *next in my structure in order for this technic to work. I will free the whole grid only at exit time.
kornalius wrote:I will probably use the same technic I used in another part of my program where once the object (structure) is assigned I don't free it and just use a pointer to move to the next or previous object and create a new one only when neccessary. I will have to add a tgrid *next in my structure in order for this technic to work. I will free the whole grid only at exit time.

If each sprite is going to occupy at most one grid location, you could store the next pointer as part of the sprite.

- HM