huazi

huazi

Android Performance Optimization Summary

title: Summary of Android Performance Optimization
date: 2017-04-01 23:39:21
tags:

  • Android
  • Performance Optimization
    categories:
  • Android

As a mobile device, Android devices are limited in terms of both memory and CPU performance. Therefore, Android cannot use memory and CPU resources without limitations. Excessive use of memory can lead to memory overflow, also known as OOM (Out of Memory). Excessive use of CPU resources can cause the phone to become sluggish or even unresponsive, known as ANR (Application Not Responding). Therefore, performance issues in Android programs have become prominent. This requires us to pay attention to performance optimization in our everyday coding. The prerequisite for optimization is to clearly understand the situations that can cause performance problems. The following summarizes some methods for performance optimization.

1. Layout Optimization#

The idea behind layout optimization is simple: minimize the number of layers in the layout file to reduce the workload of drawing. How to optimize the layout?

  • First, remove unused controls and layers from the layout. Then, selectively use ViewGroup. For example, both LinearLayout and RelativeLayout can be used, but LinearLayout should be chosen because RelativeLayout is more complex and consumes more CPU time during the layout process. In addition, reducing nesting is a commonly used and intuitive method.

  • Use the <include> tag, <merge> tag, and ViewStub. The <include> tag is mainly used for layout reuse, the <merge> tag is used to reduce nesting and can be used together with the <include> tag or in custom views. The ViewStub provides on-demand loading functionality. It is very lightweight with a width and height of 0, so it does not participate in layout and drawing. Many layouts are not displayed under normal circumstances but only displayed in specific scenarios. Therefore, they only need to be loaded when they need to be displayed, which can improve initialization performance.

2. Drawing Optimization#

Drawing optimization refers to avoiding performing a large number of operations in the onDraw method of a View, which is mainly reflected in two aspects.

  • First, do not create new local objects in onDraw because onDraw is called frequently. This will instantly generate a large number of temporary objects, which not only consumes excessive memory but also leads to frequent garbage collection (GC), reducing program execution efficiency.

  • Second, do not perform time-consuming tasks or execute a large number of loop operations in the onDraw method. Although each loop is lightweight, a large number of loops still aggressively occupy CPU time slices, resulting in an unsmooth view drawing process. According to Google's official performance optimization standards, the optimal frame rate for View drawing is 60fps, which requires that the drawing time per frame does not exceed 16ms (16ms = 1000/60).

3. Memory Leak Optimization#

Memory leak optimization requires developers to have experience and awareness. It is also one of the most common mistakes. Memory leak optimization mainly involves two aspects: avoiding writing code with memory leaks during development and finding potential memory leaks through analysis tools and resolving them. Here are some coding situations that are prone to memory leaks:

  • Static variables causing memory leaks

    For example, if Context or View is a static variable and it internally holds an Activity, it cannot be released even after the Activity is closed.

  • Memory leaks caused by singleton pattern

    It is similar to the previous case, where a direct reference to an object holds an Activity, preventing it from being released. Another less obvious case is when registering a listener without unregistering it, which can also cause memory leaks. Because the characteristic of a singleton is that its lifecycle is consistent with the Application, it can cause memory leaks.

  • Memory leaks caused by property animations

    Property animations are a type of infinite loop animation. If this type of animation is played in an Activity and not stopped in onDestory, the animation will continue to play because the Activity is held by the animation View, preventing the Activity from being released. The solution is to stop the animation in a timely manner.

There are many tools for analyzing memory leaks, such as:

  • Profiler in Android Studio

    It provides a visual display of CPU, memory, and network changes, and can perform many simulation operations. However, it is not easy to identify memory leaks and needs to be used in conjunction with MTA.

  • MAT (Eclipse Memory Analyzer)

    MAT is a powerful memory leak analysis tool.

  • Android LeakCanary

    Android LeakCanary is easy to integrate and automatically detects memory leaks, making it very useful. Currently, we also use LeakCanary in our project. Refer to the documentation for usage instructions.

These tools help us analyze and locate the position of memory leaks. Once we know where the problem is, we can solve it.

4. Response Speed Optimization#

The core idea is to avoid performing time-consuming operations in the main thread. When there are time-consuming operations, they should be performed in a separate thread. Slow response speed is generally reflected in the startup speed of an Activity. When the main thread is overloaded, it can cause a black screen or even ANR.

  • Perform time-consuming operations in a separate thread.
  • Optimize business logic, such as using new algorithms, code refactoring, repaying historical debts, etc.
  • Analyze the trace.txt file to locate the cause of ANR.
  • The main thread and sub-threads compete for synchronization locks, and the sub-threads hold the locks required by the main thread.

5. RecyclerView and Bitmap Optimization#

  • Avoid performing time-consuming operations in onBindView.
  • Control the frequency of task execution based on the scroll state of the list. For example, it is not suitable to start a large number of asynchronous tasks when the list is scrolling quickly.
  • For Bitmap, mainly use BitmapFactory.Options to sample the image according to the needs, load appropriately sized images, and reduce the size of the Bitmap.

6. Thread Optimization#

Thread optimization mainly involves using thread pools to avoid having a large number of Thread objects in the program. Thread pools can reuse internal threads, avoiding the performance overhead of creating and destroying threads. At the same time, thread pools can effectively control the maximum concurrency of threads, avoiding the occurrence of blocking due to resource contention among a large number of threads. Therefore, it is recommended to use thread pools as much as possible during development instead of creating a new Thread each time.

7. Optimization Suggestions#

  • Avoid creating too many objects.
  • Do not use enumerations excessively, as enumerations occupy more memory space than integers.
  • Use static final to modify constants.
  • Use some Android-specific data structures, which have better performance.
  • Use soft references and weak references appropriately.
  • Use memory caching and disk caching.
  • Use static inner classes as much as possible to avoid potential memory leaks caused by inner classes.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.