Android Memory Optimization Series:
- Android Code Memory Optimization Suggestions - Android (Official)
- Android Code Memory Optimization Suggestions - Java (Official)
- Android Code Memory Optimization Suggestions - Android Resources
- Android Code Memory Optimization Suggestions - OnTrimMemory
This article covers micro-optimizations in Android Java code. Choosing suitable algorithms and data structures still comes first; these techniques are most useful for reducing repeated work and temporary allocations in hot paths.
The original source was Google’s Android Training article, Performance Tips. “Java (Official)” in the title refers to its Java coding advice for Android, not to an Oracle Java performance specification.
Technical review: October 13, 2026. The old fixed speed ratios, some string implementation details, and compiler limitations are outdated as general Android advice. The original 11 topics are retained below, with their historical context and current use separated. The historical source is available in AOSP android-5.1.1_r1.
Introduction
Efficient code should avoid two kinds of overhead:
- Unnecessary repeated work.
- Temporary allocations that can be removed from hot paths.
Saving one allocation does not justify breaking an interface or complicating state management. Performance also depends on the CPU, OS, runtime, and compilation state. Android 7.0 (API 24) introduced an ART JIT that works alongside AOT; a method may be interpreted, JIT-compiled, or AOT-compiled. The old rankings based simply on “with or without JIT” do not describe every current release build. See the Android 7.0 JIT/AOT notes and ART JIT documentation.
1) Avoid Creating Unnecessary Objects
GC can reclaim unused objects, but allocation and collection have costs. Start with short-lived objects in frequently executed code, rather than counting every new in the source.
- If a method’s returned string is only ever appended to an existing
StringBuffer, it can append directly to that buffer and avoid an intermediate string.StringBuilderis also suitable for single-threaded concatenation; do not introduce shared mutable buffers just for this optimization. - The old advice to use
substring()relied on sharing the originalchar[]. This implementation is visible in Android 4.4.4’s Dalvik String source, but retaining a small substring could retain the entire backing array. The currentString.substring()contract specifies the character range returned, without promising zero-copy behavior or shared storage. The old implementation is not a portable memory-saving technique.
Choose array layouts for the data being represented. An int[] avoids an object reference for each element and is generally more compact than boxed Integer[], but cannot represent null. The original discussion compared arrays of (int, int) or (Foo, Bar) tuple objects with two parallel arrays, which avoid the tuple objects. It did not establish that splitting any two-dimensional array makes it faster. Parallel arrays also require their indices to remain aligned; measured allocation or memory pressure should justify that maintenance cost.
Reducing temporary allocations can reduce GC pressure. One allocation does not imply one GC, and a smaller object count alone does not guarantee smoother UI.
2) Prefer Static Over Virtual
Declare a method static when it does not semantically belong to an instance and does not need instance-method overriding. The old “15%–20% faster” figure describes early runtime behavior; current results depend on inlining, the call site, and the compiled output.
static means there is no implicit this, not that the method has no side effects. It can still modify static fields or objects passed to it. Do not change a polymorphic interface just to chase that old ratio.
3) Use Static Final for Constants
Consider these field declarations:
1 | static int intVal = 42; |
These assignments become part of the class initializer, <clinit>. After initialization, ordinary field reads do not rerun <clinit> on every access.
For constants, use:
1 | static final int intVal = 42; |
Both fields here are compile-time constants, so references can use their constant values directly. Under Java SE 25 JLS §4.12.4, a constant variable must be final, have a primitive or String type, and be initialized with a constant expression. An arbitrary static final object reference, or a value returned by a method call, does not meet that rule. A reference that cannot be reassigned can still point to a mutable object.
4) Avoid Internal Getters/Setters
This heading retains the historical advice, but calling getters “bad practice on Android” is no longer a useful rule. Direct access to a simple field within its class can be clear. Bypassing an accessor that performs validation, lazy initialization, or synchronization changes behavior.
The old 3x and 7x figures do not represent current ART in general. R8 at build time and runtime compilers can inline simple methods, but the result depends on the output and must be measured. R8 became the default code shrinker in Android Gradle Plugin 3.4.0; that does not mean shrinking and optimization are enabled for every build. Check the actual release configuration. See the AGP 3.4.0 release notes and app optimization setup.
Keep useful encapsulation and compare access patterns only in confirmed hot paths.
5) Use Enhanced For Loop Syntax
The three methods below calculate and return a sum using different loop forms. They illustrate syntax; this is not a microbenchmark that establishes a ranking:
1 | public class LoopExamples { |
The original ranking of zero(), one(), and two() depended on limitations of the JIT at the time. It does not prove that zero() is always slowest today or that manually caching the length always helps.
Enhanced for has two cases. Under JLS §14.14.2, array traversal is translated into an indexed loop, while traversal of an Iterable uses an iterator. An array for-each does not create an iterator just because it uses that syntax. For an Iterable, actual allocation and dispatch costs depend on its implementation and optimization.
For arrays, readability is usually a good starting point. An indexed loop over an ArrayList can be a candidate in a hot path, but this does not establish a faster pattern for all collections. It also does not remove the need to consider the semantics of modifying a collection during traversal.
6) Use Package Access Instead of Private Access for Inner Classes
This is another historical recommendation that needs a version boundary. In the following example, calling new Foo().run() prints Value is 27:
1 | public class Foo { |
Java permits this inner class to access the outer class’s private members. Older compilation pipelines generated synthetic methods with names such as access$100 and access$200 to bridge the VM’s access rules at the time. These names are compiler details, not APIs to write by hand.
Java 11 introduced JVM nestmate access, allowing classes in the same nest to access each other’s private members; see JVMS 11 §5.4.4. Android APKs also pass through D8/R8 to produce DEX, so the desktop JDK version alone cannot prove whether helper methods survive in the final output.
Use private where encapsulation requires it. Package access exposes a member to other classes in the package. Consider changing it only after identifying meaningful overhead in the final output and evaluating that visibility change.
7) Avoid Float
This old recommendation is outdated. “Float is half as fast as int” is not an Android API guarantee or a fixed ratio for all floating-point operations and memory accesses. The outcome depends on the processor, instructions, data dependencies, and optimization.
Choose types for the required range, precision, and algorithm. Replacing fractional arithmetic with integers can change results through truncation or overflow. Compare alternatives that preserve the numerical requirements only after locating a bottleneck.
8) Use Library Functions
Prefer library operations whose semantics match the task, such as System.arraycopy(). Its contract defines type checks, bounds checks, and copying between overlapping regions; a manual implementation must handle those conditions too.
The old “over 9x faster” figure specifically referred to a Nexus One with JIT enabled. It is not a current performance guarantee. Results depend on array types, lengths, and the target device. Library calls should not be described as always executing through JNI, either.
The original reference to Effective Java, second edition, Item 47 (“Know and use the libraries”), corresponds to Item 59 in the third edition.
9) Use Native Methods Sparingly
JNI can be evaluated when porting an existing native library or addressing a measured compute hotspot. Include the costs of crossing the boundary, converting data, and copying it; timing only the native function’s body misses part of the work.
Reduce frequent small cross-boundary interactions and define ownership of native resources and JNI references. The current Android NDK guide is JNI Tips.
10) Performance Myth: Concrete vs. Interface
Map<K, V> map = new HashMap<>(); and a variable declared as HashMap<K, V> can refer to the same implementation. This comparison concerns the declared type and method dispatch at a call site, not the data-structure performance of two different containers.
The old “about 6%” and “almost no difference with JIT” figures also depended on their runtime environment. Choose types for the interface design, then inspect optimization in measured hot paths. An unmeasured dispatch difference is not a reason to replace every Map declaration with HashMap.
11) Measurement
The original Dalvik-era Traceview measurements were affected by method tracing’s interaction with JIT. That does not mean all profilers disable JIT, or that uninstrumented execution can be estimated as merely a little faster.
Traceview is deprecated; the official guidance recommends CPU Profiler for Android Studio 3.2 and later. Use Android Studio Profiler or Perfetto to locate hotspots, then choose the measurement scope:
- Jetpack Microbenchmark compares identified methods or loops, handles warmup, and measures timing and allocations. Use representative inputs and consume results so unused computation cannot be optimized away.
- Macrobenchmark and app performance measurement cover user flows such as startup and scrolling, showing whether a local optimization improves the experience.
Control the device, OS, build configuration, and compilation state. Measure on physical devices using a suitable non-debuggable build, and record warmup and sampling conditions. Debug builds, emulator results, and different compilation states should not be mixed into one ranking.
About Me && Blog
Here are my introduction and related links. I welcome conversations with fellow developers and opportunities to learn from one another.
- About me: contact details and WeChat groups.
- Blog navigation: a guide to this blog’s articles.
- Android Performance Optimization: Essential Skills and Tools: recommendations and contributions are welcome through WeChat.
- Android Performance community: The paid community stopped operating in 2026 and no longer accepts new members; this link preserves its history.
If you want to go fast, go alone. If you want to go far, go together.
