Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reliable memory info on mobile devices?

I am currently working on an app that runs on iOS and Android. The core of the app is written in C++ and allocates over time more and more memory. The thing is I want at the same time to be able to use as much memory as possible and ensure the stability of the app.

Of course, to do that I would need to know how much memory I can still use. This way, if I see after a while that I am going to need more than it is available, I could stop allocating instead of getting killed by the OS or crashing.

The problem is, after reading and trying different solutions, my feeling is the information that you dynamically get is not reliable enough. For instance, on iOS:

[NSProcessInfo processInfo].physicalMemory

This is one of the typical examples / answers I have read that seems not to be reliable. It seems that you cannot get enough information dynamically to make sure that you still have enough memory, because the OS will at some point kill your app if it uses too much memory and sends warnings before. But it also can kill other apps in between, so stopping when I receive the first one seems not to be an optimal solution.

After reading a lot of posts, I am a bit confused on the topic. Is there a way to know dynamically and reliably how much memory is left for my app on iOS/Android ? Or memory management from these OS is too unpredictable for that ?

Thanks for the help !

like image 780
Matthieu P. Avatar asked May 28 '15 09:05

Matthieu P.


1 Answers

By design, you're prohibited by the operating system from ever using up all the physical memory on the device; what's more, the requirements of the operating system and the other apps running on it mean that the amount of memory your app can comfortably use will vary over time.

Therefore asking how much memory you have left to use isn't really sensible. You should design your app to use as little memory as possible, and then optimize until you use less than that.

  • Be aggressive about caching things out to disk.
  • Listen to the OS-provided notifications that your memory is under pressure.
  • Design your app in such a way that you can restore its last UI state from fresh launch: app launches and task switches are presented to the user the same way, and they won't and shouldn't need to know the difference.

If you do use more and more memory, the OS will try and terminate other apps to make room for yours. That means, bye bye Facebook, bye bye Twitter, bye bye Mail, bye bye Contacts. Your users will notice, and they will choose to launch your app less often, or review it less favorably, as a result.

like image 179
damian Avatar answered Sep 17 '22 16:09

damian