August 13, 2021

Best practices for Memory management so reduce OutOfMemory crash

By lj007

Android provides such a huge range of devices with different different configuration. For developer it is necessary to keep in mind that if device with 8GB ram available, then also device with 512MB ram available. To create a good app developer should take care of this.

Here you can find general tips for memory optimization which will help you reduce your memory usage :

  • Avoid creating unnecessary objects. If you can do your work with only two variables then try it, do not create unnecessary objects.
  • Some beginners like me don’t think about creating temp objects in loop. But this requires more memory. For example, if you are creating an ArrayList<CustomObject> from JSON response, then you are going to use loop and in loop you are using tempVariable of CustomObject and then add it to list. This may be west of memory. Instead of this you can create CustomObject’s object outside loop and reuse same.
  • Reuse same object whenever is possible to do so.
  • Do not use superclass for default data types like integer or boolean. An object of “Integer” requires 16 bytes for one object when an object of “int” requires only 4 bytes. Be aware of this.
  • Always avoid to use enum in Android. Instead of this use static final variables for constants.
  • Avoid anonymous inter classes, because it uses about 500 bytes of code. And it retains in memory till your super class frees.
  • Abstract class is good for use, but be careful with it. Only use it whenever it provide a significant benefit.
  • Try to avoid static variables or objects as much as possible if they are not final constants.
  • Avoid internal getter and setter methods. Direct field access is much faster in Android then virtual method lookup.
  • A common mistake is to save “Context” objects everywhere in the Application. If the developer forgot to free even one reference of context, it increase the chance of  a whole Activity leak.
  • For passing information between components of same application, avoid using IPC mechanisms like Intent and ContentProviders if possible. Work with handlers, listener interfaces instead.

This is my own research from search engine,  This may be wrong, but it helps me a lot.