Sometimes, when I unload assets from my game, the max used memory goes down with the in-use memory, and I don't know if I understand correctly what this max used value means or if there is something strange going on.
I think this is causing some memory problems in my game, because I'm sure that the game is crashing if the max-used value is too high when I load some new assets into memory, even though the in-use value is low.
I'm on 3.1.1 and I use Lua
I hope that someone has an explanation for this. Thank you
If I hadn't chopped off the bottom you'd see In Use: 3075.42 KB, Max Used: 3144.78 KB. This is the game heap. The entire green and red area is 3144.78 KB, but just the green parts total 3075.42 KB. The red is memory that was previously allocated but has since been freed. And everything past the green hasn't been allocated yet. There's around 70 KB of freed space in the heap but the largest block is only 15 KB or so, so if you ask the allocator for more memory than that it has to extend the heap out to make more room. In this example there's plenty of space, so no problem.
But you can imagine what happens if we keep allocating small chunks of memory and freeing only some of them: We push the heap all the way to the end of available memory and there might be a lot of freed memory in total but it's all in tiny chunks. This is called memory fragmentation, and the best way to prevent it is to reuse allocated memory where possible. A good example is audio samples: Say you have a different bgm track for each level of your game. You'll want to create a single static playdate.sound.sample that fits the longest track (plus an extra 44 bytes because of this bug) and use sample:load() to load the data into the sample instead of continually allocating and freeing sample objects. Images and image tables have similar functions for loading new data into existing buffers.