Android memory optimisation is often a demanding task, especially for novice developers. Autoboxing is a topic that often goes unnoticed when talking about performance issues. However, you should keep it in mind, and make use of tools and structures that Android SDK provides.

Let me remind you all what autoboxing really is:

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types (int, double, bool) and their corresponding Java classes (Integer, Double, Boolean). Reverse conversion is called unboxing. For example:

Memory usage by each primitive types are as follows:

These types are great for matching their hardware definitions, but they can’t be used with generics collections (see this topic if you are interested why). Instead Java language provides corresponding classes that match primitives types, and act as object wrappers. These classes give you the same functionalities as primitives but can be used with generic collections. However their size in memory is not the same. For example Integer class holds 16 bytes in memory, rather than 4 for primitive. It also requires more overhead to access the underlying value.

It can be especially painful with data structures like HashMap. Consider following code:

Operations put and get will use autoboxing and cause additional load. Basically anytime you insert , update or retrieve a value with this generic container when an primitive is involved you end up boxing or unboxing values. This the exact reason why Android Platform provided custom containers like SparseArrays to use instead of traditional containers like HashMap. These containers were design specifically to fight autoboxing problem and eliminate both runtime overhead and additional memory allocation.  Look up below.

This way you make your code more optimised and memory efficient.

To look for places in code where autoboxing could be causing a problem use Android Studio tools like AllocationTracker and TraceView. More about finding memory issues soon.