Justin Meiners Justin Meiners - 1 year ago 66
C Question

Is it slow on the iPhone to do a lot of mallocs and frees?

I was working on some particle systems and this was the only way I could figure out to set up the arrays:

if (vertices){
if (textures){
vertices = malloc(sizeof(point3D) * 4 * [particles count]);
textures = malloc(sizeof(point2D) * 4 * [particles count]);

The particles constantly change so a new size of array needs to constantly be created at about 60 fps. Is this a bad way of doing things? Could this cause my app to slow down or cause memory thrashing? When I run it under instruments it doesnt look too bad but it is running on the simulator on my Mac. Is this ok or is there another way I could be doing this?

Ok I went in and rewrote the system it estimates the max amount of particles at creation. Then it uses that to allocate arrays. This system has the trade off that it often overestimates the memory needed by quite a bit but only calls malloc once. I figured it was not that big of a trade-off since a maximum realistic overestimate would be like 100 floats, which is not too bad. Thanks for the help guys.

bta bta
Answer Source

Try starting with an estimated particle count and malloc-ing an array of that size. Then, if your particle count needs to increase, use realloc to re-size the existing buffer. That way, you minimize the amount of allocate/free operations that you are doing.

If you want to make sure that you don't waste memory, you can also keep a record of the last 100 (or so) particle counts. If the max particle count out of that set is less than (let's say) 75% of your current buffer size, then resize the buffer down to fit that smaller particle count.