Best memory allocation strategy for iOS?

| | August 7, 2015

I’m debating myself about memory allocation on iOS. I write most of my code in C++ and I really like using ObjectPools, FreeLists, etc. In order to pre-allocate a lot of the stuff that I’ll be constantly “alloc/dealloc” during the course of my game, ( like particles, game entities, etc ).

Still on iOS, it’s not like we are developing for a console like PSP, where I can know for fact that I’ll get a fixed amount of memory. iOS , will issue “memory warnings” when the system needs memory.

Does anyone have some suggestions about this ? Is it too serious since the new iPod touch/iPhone 4 are carrying more RAM ? or it’s still a big concern?

2 Responses to “Best memory allocation strategy for iOS?”

  1. To tack on a note to 5ound’s answer: pay attention to the level of the memory warning. Prior to iOS 3.2 there was no way to distinguish between warnings of different severity (i.e. is the OS just sitting on a bunch of UIImages it can clear or is there really no memory left?). in 3.2 onwards you can check the level of the memory warning to determine how to react. In my experience level 1 warnings are constant, unavoidable and largely meaningless, so I wouldn’t take drastic action in response to them. Although level 2 warnings are not necessarily a sign of impending doom you should probably take them seriously and start clearing any caches you can, etc.

    There’s a good discussion of the different levels here:

    P.S. – This is more of a comment to 5ound’s answer but I don’t have enough rep to comment so this was my only option…

  2. Use your common memory management sense. Use pools/freelists for things that are frequently allocated and deallocated (i.e. particles), free memory blocks that aren’t in use. However, don’t try to preallocate large chunks of memory upfront. iOS doesn’t guarantee memory nor does it swap, so any memory you have allocated is taking resources away from the system and other apps. If the system cannot get enough memory because your application is hogging all of it, then it will resort to killing your app. You should handle the applicationDidReceiveMemoryWarning for what it was designed for by deallocating as much memory as possible. Although iPhone 4 has lots of memory, but with all the multitasking features and the way people tend to use them, you may actually have less memory than you think.

    (Also, don’t forget to profile your app to see whether memory allocation is a bottleneck!)

Leave a Reply