Android Performance Optimization Video

Source: Internet
Author: User
Tags try catch

Han Mengfei sha Han Yafei [email protected] yue31313 Han_meng_fei_sha

Android-Performance optimized memory leak-Original-HD video-Iqiyi

=========

Android phone memory management and performance optimization video tutorial download

Download: http://pan.baidu.com/s/1skkSdI1 Password: KDCs

01.Dalvik introduction and its advantages and file formats

02. Stack-based vs. Register-based comparisons

03.DEX and Odex file format and Odex detailed

04.GC garbage collection mechanism

05. Memory Monitoring Analysis Tool DDMS Introduction

06. Memory Allocation Tracking Tool Ddms_alocation Tracker Detailed

07. Introduction of monitoring tools and analysis tools and file Explorer

08. Releasing references to objects and using context

Improper use of 09.Adapter and picture processing and cyclic variables

10. Querying the database and static keyword usage and threading

11. Comparison of self-methods and virtual statics and final constants

12. Image processing optimization and use of class libraries and finally blocks

13.android4.4 new features Dalvik replaced by art and enterprise face test in this chapter

14.JNI explanation of the principle

15.JNI Architecture in a detailed

16.NDK and JNI Relationship description and NDK development environment construction

17.NDK Configuring the environment to compile the project and import the eclipse run

18. Install plug-ins and JNI environment configuration and NDK development process

Advantages and disadvantages of 19.JNI and how to use JNI properly

20.Java how to tell how data is passed to C and C callback Java methods

21.C access to Java code running mechanism anatomy

The role of 22.JNIENV pointers and design ideas and design advantages

23. Get jnienv pointers and Jobject and Java inheritance relationship and jobject role

24. Instructor recommended JNI and NDK articles online

25. Get an example of a class object for Java classes

26. Accessing methods and properties and sign signatures in Java

27. Summary of the contents of this chapter online

Five common methods in a 28.Java string

Five common methods in 29.Java string two

30. Array of primitive types and arrays of object types

31. For two types of arrays without classes and global and local and weak global references

32. Cache handling and exception handling and exception mechanism flow

33.cc++ and Android threading patterns and calling cc++ code in Java

Multithreading calls Java code and summary in 34.cc++

=========

1. Memory Leak

Memory leaks: For Java, the new object placed on the heap cannot be reclaimed by GC (objects that cannot be reclaimed in memory), and memory leaks occur primarily in memory jitter, with less usable memory.

1.1 Memory Monitor

The memory monitor of the Androidstudio can easily observe the allocation of the heap ram, and can be used to see if there is any memory Leak.

Frequent memory jitter, possible memory leaks

A:initiate GC Manual triggering of GC operation;

B:dump Java Heap Gets the current stack information, generates a. hprof file, Androidstudip automatically opens with Heapviewer, and typically detects a memory leak after the operation;

The C:start Allocation Tracking memory allocation tracking tool is used to track memory allocation usage over time and to know which objects are allocated space after performing some column operations. Typically used to track memory allocations after an operation, adjust the associated method to optimize app performance and memory usage;

D: Remaining available memory;

E: Memory already in use.

Clicking on the dump Java Heap of memory monitor will generate a. hprof file, and Androidstudio will automatically open with Heapviewer.

Hprof Viewer opens the. Hprof file

Left panel Description:

    • Total count the number of instances of the class
    • Heap count the number of instances in the heap selected
    • Sizeof The amount of memory that each instance occupies
    • Shallow size all instances of this class occupy memory
    • Retained size The amount of memory that can be dictated by all instances of the class

Right Panel Description:

    • Instance all instance objects of the class (left total count is 15, there are 15 objects)
    • Depth depth, the shortest link of the GC root point to the instance
    • Dominating size The amount of memory the instance can dictate

Here you can see that there are 15 sample objects in Mainactivity and suspect there is a problem here.

1.2 MAT

The above can only be rough to see if there is a problem, and you need to know where the problem is the use of mat. Convert the generated. hprof file and use the mat to open it;

Format Conversion command: Hprof-conv file path after original file path conversion

Mat Open. Hprof

Note the following actions:

    • Histogram can list the name, number, and size of each object in memory.
    • Dominator Tree sorts all in-memory objects by size, and we can parse the reference structure between objects.

The most commonly used is also these two functions.

The retained heap represents the total memory occupied by this object and other references it holds (both direct and indirect)

    • Using histogram:
    • Clicking Histogram and typing mainactivity at the top of the regex will make a regular match, listing all objects containing "mainactivity", where the first line is an instance of mainactivity.

    • For the object you are looking for, right-click List objects, with incoming references view specific mainactivity instances.

    • Right-click the Path to Gc Roots, exclude weak reference (excluding soft references) for the object instance you want to view.

Attention:

There is a circle in the lower left corner of the icon in front of the this$0, which means that the reference can be referenced by the GC roots, because Mainactivity$leakclass can be accessed by the GC roots to prevent it from being recycled, so that other references it holds cannot be recycled. Includes mainactivity and other resources included in the mainactivity.

At this point we find the cause of the memory leak.

    • Using Dominator Tree

The specific cause of the leak can also be found using the histogram above, which is no longer described here.

Note: The circle of the icon in front of each object does not necessarily cause a memory leak, some objects need to survive in memory and need to be treated differently.

1.3 Leakcanary

Leakcanary is a library that detects memory leaks in square, which is integrated into the app without care, prompts for a toast, notification bar popup After a memory leak, and can indicate a leaked reference path, and can crawl the current stack information for detailed analysis.

2. Out of Memory

2.1 Android OOM

Each process in the Android system has a maximum memory limit, and the system throws an oom error if the requested memory resource exceeds this limit.

    • On Android 2.x system, oom occurs when Dalvik allocated + external allocated + newly allocated size >= Dalvik heap maximum. Where bitmap is placed in the external.
    • Android 4.x system, the external counter is abolished, the distribution of similar bitmap is changed to Dalvik Java heap application, as long as allocated + newly allocated memory >= Dalvik Heap maximum value will occur when Oom ( The statistical rules of the art operating environment are still consistent with Dalvik)

A memory overflow is the final result of a program running to a stage, the direct reason is that the remaining memory does not meet the memory request, but then analyzes the indirect reason why the memory is gone:

    • The presence of memory leaks can lead to less usable memory;
    • The peak memory request exceeds the memory remaining at the system point in time, (for example: a single process can have a maximum memory of 192M, the current allocation of memory 80M, at this time the request for 5 m of memory, but the current point of the total system available memory is only 3 m, there is no more than a single process available maximum memory, Oom also occurs)

2.2 Avoid Android OOM

In addition to avoiding memory leaks, according to the Manage Your App's memory, we can listen to the state of the RAM, overwrite this method in the activity, and handle it differently depending on the case:

    1. @Override
    2. Public void Ontrimmemory (int. level ) {super.ontrimmemory (level);
    3. }

Trim_memory_running_moderate: Your app is running and will not be listed as a kill. However, when the device is running in a low memory state, the system starts triggering a mechanism to kill the process in the LRU cache.

Trim_memory_running_low: Your app is running and not listed as a kill. However, when the device is running in a lower memory state, you should free up unused resources to improve system performance.

Trim_memory_running_critical: Your app is still running, but the system has already killed most of the processes in the LRU cache, so you should release all non-essential resources immediately. If the system is not able to reclaim enough RAM, the system clears all the processes in the LRU cache and starts killing processes that were previously thought not to be killed, such as the one containing a running service.

You may receive one of the following values returned from Ontrimmemory () when the application process has retreated to the background while it is being cached:

Trim_memory_background: The system is running in a low memory state and your process is in the most vulnerable location in the LRU cache list. Although your application process is not in a high-risk state of being killed, the system may have started to kill other processes in the LRU cache. You should release the resources that are easy to recover so that your process can be preserved so that you can recover quickly when the user rolls back to your app.

Trim_memory_moderate: The system is running in a low memory state and your process is already close to the central location of the LRU list. If the system starts to become more memory intensive, your process is likely to be killed.

Trim_memory_complete: The system is running in a low-memory state and your process is in the most easily killed position on the LRU list. You should release any resources that do not affect the recovery status of your app.

3. Memory Churn

Memory Churn: A large number of objects are created and released in a short period of time.

Generating a large number of objects in an instant can seriously occupy young generation's memory area, and when the threshold is reached, the GC will also be triggered when there is not enough space left. The more time the system spends on GC, the less time it takes for the interface to draw or stream audio processing. Even though each allocated object consumes little memory, stacking them together increases the pressure on the heap, triggering more other types of GC. This operation has the potential to affect the frame rate and make the user aware of performance issues.

Drop Frame occur

Common scenarios in which memory jitter can occur:

    • Creates a temporary object in a loop;
    • Create Paint or Bitmap objects in OnDraw;

For example, the implementation of some of the previously used pull-down refresh controls, creating multiple temporary large objects such as bitmap in OnDraw can cause memory jitter.

4. Bitmap

Bitmap processing is also a difficulty in Android, of course, using a third-party framework to block out the difficulty.

    • Bitmap's memory model;
    • Bitmap loading, compression, caching and other strategies;
    • Compatibility of the version, etc.;

About bitmap will write a special article to introduce, here can refer to "Handling Bitmaps".

5. Program Advice

5.1 Use of service in moderation

One of the biggest errors in memory management is to keep the service running. When a service is used in the background, the service should be in a stopped state at other times unless it needs to be triggered and a task is executed. It is also important to be aware that service work is completed and needs to be stopped to avoid memory leaks.

The system tends to retain the process where the service is located, which makes the process expensive to run because the system has no way to free up the RAM space occupied by the service for other components, and the service cannot be paged out. This reduces the number of processes that the system can store into the LRU cache, which can affect the efficiency of switching between applications, and may even cause system memory usage to be unstable, thus failing to maintain all currently running service.

It is recommended to use Jobscheduler and avoid using persistent service as much as possible. It is also recommended to use Intentservice, which will end up as soon as possible after handling the tasks given to it.

5.2 Using an optimized collection

The Android API provides a number of optimized data collection tool classes, such as Sparsearray,sparsebooleanarray, and Longsparsearray, which can be used to make our programs more efficient. The HashMap tool class provided in the traditional Java API is relatively inefficient because it requires an object entry for each key-value pair, and Sparsearray avoids the time when the base data type is converted to the object data type.

5.3 Caution towards abstraction

Developers often use abstraction as a good programming practice, because abstraction can improve the flexibility and maintainability of code. However, abstraction can lead to a significant overhead: An abstraction requires additional code (which is not executed), which is also mapped into memory, consuming more time and memory space. So if there is no significant benefit to your code for an abstraction, you should avoid it.

For example, using enumerations typically consumes more than twice times more memory than using static constants, and in Android development we should use enumerations as little as possible.

5.4 Serialization of data using Nano Protobufs

Protocol buffers is a language-independent, platform-independent, well-extensible data-Description language designed for serialized data, similar to XML, but lighter, faster, and simpler. If you use Protobufs for serialization and deserialization of data, it is recommended that you use Nano Protobufs on the client side, because the usual PROTOBUFS generates redundant code, which results in less usable memory, a larger apk volume, and slower operation.

5.5 Avoiding Memory Jitter

Garbage collection typically does not affect the performance of your app, but multiple garbage collection over a short period of time consumes the time it takes to draw the interface. The more time the system spends on GC, the less time it takes for the interface to draw or stream audio processing. Usually memory jitter results in multiple GC, in practice memory jitter represents a temporary object allocated over time.

For example, when multiple temporary objects are allocated in a For loop, or a paint, bitmap object is created in the OnDraw () method, the application produces a large number of objects, which quickly depletes the available memory of young generation, causing the GC to occur.

Use the tools in analyze your RAM usage to find out where the memory jitter is in the code. Consider moving the operation out of the internal loop or moving it into a factory-based allocation structure.

5.6 Remove the memory-consuming library, reduce the size of the APK

Look at the size of the APK, including the three-party library and the embedded resources, which can affect the memory consumed by the application. By reducing redundancy, non-essential or large components, libraries, pictures, resources, animations, and so on, you can improve your application's memory consumption.

5.7 Using Dagger 2 for Dependency injection

If you intend to use the dependency injection framework in your application, consider using Dagger 2. Dagger does not use reflection to scan the application's code. Dagger's compile-time annotation technology implementation means that it does not require unnecessary runtime costs. Other dependency injection frameworks that use reflection typically initialize the process by scanning the code. This process may require significantly more CPU cycles and RAM, and may cause noticeable lag in application startup.

Note: A dependency injection framework is not recommended for previous documents because the implementation principle is to use reflection and evolve to compile-time annotations without the effect of reflection.

5.8 Prudent use of third-party libraries

Many of the open Source library code is not written for the mobile side, if used on mobile devices, and not necessarily suitable. Even a library designed for Android requires special care, especially if you don't know what the library has done specifically. For example, one of the libraries uses the Nano Protobufs, and the other one uses the Micro Protobufs. This way, there are 2 ways to implement PROTOBUF in your application. Similar conflicts can occur in output logs, loading images, caches, and so on. Also do not import the entire library for 1 or 2 functions, and if you do not have a suitable library to match your needs, you should consider implementing it yourself rather than importing a chatty solution.

6. Other

6.1 Cautious use of the Largeheap property

You can declare a larger heap space for your app by adding the properties of Largeheap=true under the Application tab of manifest (you can get to this larger heap size threshold by Getlargememoryclass ()). However, the claim for a larger heap threshold is intended for a small number of applications that consume large amounts of RAM (such as an editing application for a large picture). Don't be so easy because you need to use more memory to request a large heap size. Only when you know exactly where to use a lot of memory and know why the memory must be retained to use the large heap, the use of additional memory space affects the overall user experience of the system and makes each GC run longer. The performance of the system is compromised when the task is switched. In addition, the large heap does not necessarily get a larger heap. On some severely restricted machines, the size of the large heap is the same as the usual heap size.

6.2 Prudent use of multiple processes

Multi-process is really an advanced technique that can help us save and manage memory. Use caution if you want to use it, because the vast majority of applications should not run in more than one process, and if used improperly, it will even add extra memory instead of saving us memory, and need to know the drawbacks of multiple processes. This technique is more suitable for those who need to perform a separate task in the background, and the function of the foreground can be completely separated from the scene.

Here is a better way to use multi-process skills, such as we are working on a music player software, which plays the music function should be a separate function, it does not need to have any connection with the UI, even if the software is closed should be able to play the music properly. If we only use one process at this point, then even if the user shuts down the software and the service is completely controlling the music playback, the system will still retain many of the UI memory. This scenario is ideal for use with two processes, one for UI presentation and the other for continuous music playback in the background.

6.3 Possible problems with the implementation: for example, start a splash screen and release bitmap after show is complete.

Some implementations seem to have no problem implementing functionality but may actually have an impact on memory. When I looked at the bitmap object using the heap viewer, I found a picture that simply downloaded should not be loaded.

Use Heapviewer to view bitmap directly

Images that should not be loaded in memory

By looking at the code, the problem is: Download the image here as a diagram of another module, but the download method is to use the picture loader to load the bitmap and then save to the local, and save the bitmap object is not released.

Similar to the following: Home splash screen After the display, bitmap objects should be released in time.

6.4 Capturing using a try Catch

For high-risk oom code blocks such as display HD large image and so on try catch, in the catch block load non-HD pictures and do the corresponding memory recovery processing. Note that Oom is outofmemoryerror and cannot be captured using exception.

7. Summary

Memory-Optimized routines:

(1) Resolve all memory leaks

    • Integrated Leakcanary, can conveniently locate 90% of memory leak problem;
    • The Dump Java heap Gets the current stack information using mat for analysis by repeatedly entering and exiting the suspicious interface and observing the memory additions and deletions.
    • Common scenarios for memory leaks can be seen in the "Android Memory leak Analysis Experience"

(2) Avoid memory jitter

    • Avoid creating temporary objects in loops;
    • Avoid creating paint, bitmap objects, and so on in OnDraw.

(3) Use of bitmap

    • Loading a picture using a three-party library generally does not have a memory problem, but you need to be aware of the release of the image, rather than passively waiting for it to be released.
    • Use of optimized data structures
    • Use Ontrimmemory to handle different memory statuses

(4) Use of the library

    • Remove useless library, anti-compile the generated apk to see the library used, to avoid the useless Lib is still being hit into the apk;
    • Avoid introducing a huge library;
    • Use Proguard to confuse and compress.

========

========

Android performance Optimization video

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.