You really must be doing a lot of huge allocations all the time if this shows up as performance issue with profiler or debug measurements.
Anyways, as rachetfreak said - C or C++ memory allocation/free functions doesn't switch to kernel on every call. The buffer memory and give you allocations from memory pool they have.
If you want to explictly write that in your code then do what Chen96 says. I'm not sure why he calls that stack allocator, because it obviously is not stack allocator. It's a simple dynamic array. You can also implement/use resizeable array. In C++ it you would just use std::vector:
| std::vector<Sprite> sprite;
sprites.reserve(1000); // this allocates memory for initial sprites, do it outside of main loop
// now these calls most of the time won't allocate new memory
sprites.push_back(get_sprite(...));
// or a bit more efficiently, call sprite constructor directly:
sprites.emplace_back({...});
// when done, remove sprites, this does not free memory most of the time:
sprites.clear();
|
In C it's a bit of manual work to keep count of sprites:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | int count = 0;
int allocated = 1000;
Sprite* sprites = calloc(allocated, sizeof(Sprite)); // initially get space for 1000 elements
// when you want to append new one, check if you need to resize array
if (count == allocated)
{
allocated *= 2
sprites = realloc(sprites, allocated * sizeof(Sprite));
}
// now just put elements inside array, and update count
sprites[count++] = ...;
// clear out array
count = 0;
|
Or if you know limit of sprites you'll have, then simply allocate it only once, and don't keep the allocated integer. Or just put them on stack/global:
| Sprites sprites[MAX_SPRITES];
|