Share the technical essentials of Android Development performance optimization

Source: Internet
Author: User
Tags anonymous garbage collection memory usage message queue

Android performance tuning involves many aspects of work, because of my limited technical level, currently only summed up the following parts, I hope you will continue to add.

Main points

using asynchronous

Keep the APP highly responsive, don't take time-consuming actions on the UI thread, use asynchronous tasks more
Do thread control when using threads; use queues, thread pools
Use the bad Aysnctask and Timer carefully
Beware of memory leaks caused by asynchronous tasks
Asynchronous tasks should be categorized, such as HTTP, picture downloads, file read/write, asynchronous tasks for each class to maintain a task queue, not each task to open a thread (Volley said I can handle all of these _ (: З"∠) _)
These common tasks should be prioritized (general JSON data takes precedence over requests for static data such as pictures)
A general asynchronous task should open a singleasynctask to ensure that only one thread at a moment works
HTTP and picture downloads try to use the same set of network requests
Use MVP mode to standardize behavior of large activity classes to avoid memory leaks caused by asynchronous tasks

Avoid memory leaks

Understanding the virtual machine Memory recovery mechanism
Frequent GC can also cause cotton to avoid unnecessary memory overhead
Incorrect reference to the ♂ potential caused by the memory leak (ah ~ to vent ~)
Common activity leaks (single case, application, background thread, infinite animation, static reference)
Bitmap leaks (honeycomb the problem before the pressure is great)
Try to use Intentservice instead of service, the former will automatically stopitself
Ways to troubleshoot memory leaks (I've always been a simple, violent human dump check DAFA)
Use Leakcanary to automatically check for activity leak issues
Keep sensitive to memory load (SHARP)

View Optimization

Layout optimization, reduced levels, Include Merge
Use Viewstub to avoid unnecessary layoutinflate, using GONE instead of repeating layoutinflate the same layout
Avoid excessive drawing, should reduce unnecessary layout background, too deep layout level will cause excessive drawing and Measure, Layout and other methods of time complexity exponential growth
Using transition animations, such as adding a lightweight fade to a picture's rendering, makes the vision smoother.
Avoid excessive animation, do not allow an interface to appear more than one animation, such as List scrolling item to stop playing animation or GIF
Complex animations using Surfaceview or Textureview
Try to provide multiple sets of resolution pictures, using vector graphics

Adapter Optimization

Multiplexing Convertview, replacing frequent Findviewbyid with Viewholder
Do not repeat Setlistener, to use V.getid Listener, or you will create a heap of Listener resulting in frequent GC
Multiple layouts take mutilitemview instead of using a large layout and then dynamically control the parts that need to be realistic
Do not do time-consuming operations in the GetView method
To quickly scroll through a list, you can stop loading a picture of a list item, stop the animation of a list item, and not change the layout of a list item at this time
Try to use Recyclerview (increment Notify and recycledviewpool to take you flying)

Code Optimization

Algorithm optimization, reduce time complexity, refer to some classical optimization algorithms
Try to use int instead of float or double
Use basic types as far as possible, avoid unnecessary automatic boxing and unpacking, waste of time and space
Choose the Right collection class (try to change time in space), choose the Android Sparsearray,sparsebooleanarray and Longsparsearray
Avoid creating additional objects (StringBuilder)
Use the so library to complete some of the more independent functions (Gaussian blur)
Preprocessing (pre-operation) Some of the more time-consuming initialization work unified put into the boot graph processing
Lazy Loading (deferred processing) to circumvent the sensitive life cycle of activity
Log Tool class, to delete the debug code at compile time, rather than to circumvent it at runtime by judging conditions
Do you prefer a static method, a public method, or a public method? The speed difference is very big OH
Class directly to the member variable, do not use the Getter/setter method, call the method consumes extra time
External class member variables that are accessed to the inner class are declared to be accessible within the package, not private, or the method used to access the external class member variable is automatically created
When traversing the collection, use i++ instead of iterator, which requires additional object manipulation, which should be avoided in the loop body
If a basic type or String value does not change, as far as possible with final static, compile-time will directly replace the variable with the value of the variable, you do not need to query the value of the variable

Other Optimizations

Database optimization: Using indexes, using asynchronous threads
Network optimization ... A bunch of good wheels
Avoid overuse of dependency injection frameworks, large amounts of reflection
However, excessive design/abstraction, polymorphism looks very design, the price is the extra code, space, time
Try not to open multiple processes, the process is very expensive

APK Thin Body

Open confusion
Using the Zipalign tool to optimize APK
Appropriate lossy image compression, using vector graphics
Delete the redundant resources in the project and write a few scripts to delete the RES resource
Dynamic loading module, the project split Ah!

How to troubleshoot performance problems

GPU Bar chart, nothing to see Taobao
Over drawing colors, well, don't be a aunt red.
Leakcanary, automatic detection of activity leaks, very useful
TraceView (Device Monitor), Systrace, analyzes which code takes up too much CPU time
Lint, check for unreasonable res resources
Layoutopt (or optlayout?) ), proposed the optimization proposal to the current layout, has been replaced by lint, but still can use
Hierarchyviewer, look at the current interface of the mobile phone layout level, layout optimization is often used (only for the simulator, the real machine use to root, do not want to root add use Viewserver)
Strictmode, UI operations, network operations, and other areas prone to performance problems, if there is an abnormal situation strictmode will alarm


Android Memory performance optimization


Just start the children's shoes Ken can have a doubt, Java is not a virtual machine, memory will be automated management, we do not have to manually release resources, anyway, the system will be completed. In fact, there is no pointer in Java concept, but the use of pointers still exist, blindly rely on the system of GC, it is easy to create a waste of memory.


Java-based memory mechanism for garbage collection


The Java memory management mechanism automatically reclaims the memory occupied by unwanted objects and reduces the burden of manual memory management

1. C + +: From application, use, release all need manual management

2, Java: The memory of useless objects will be automatically recycled


What kind of object is a useless object

1. Java uses references to manipulate a specific object, referencing a pointer similar to C. An object can hold a reference to another object.

2. Start with a set of root objects (GC Roots), iterate through all objects by reference relationship before the object, and mark all the accessible objects during traversal. If an object is not reached by the root object, it is collected as garbage.

What are the GCRoot?

1. Class: Classes object loaded by the system's ClassLoader

2. Static Fields

3, Thread: Alive Threads

4, the Stack Local:java method of local variables or parameters

5. Local references in the JNI Local:jni method

6. JNI Global: Global JNI references

7, Monitor used: for synchronization of the monitoring objects

8. Help by VM: Objects reserved for the special purpose of the JVM by GC




Memory leaks in Java programs

The memory of an object cannot be freed from the execution logic of the program after it has been allocated and cannot be reclaimed by the memory of that object

The dangers of memory leaks

1. Cause OutOfMemoryError

2, high memory usage JVM virtual opportunity frequently triggers GC, affecting program response speed

3, memory footprint of the program is easy to be a variety of cleanup optimization program aborted, users are more inclined to uninstall these programs

The development language for Android applications is Java, and the maximum available heap memory per application is limited by the Android system

Android each application heap memory size is limited

1, the usual situation for 16m-48m

2, through the Activitymanager getmemoryclass () to query the available heap memory limits

3, 3.0 (Honeycomb) over the version can be largeheap= "true" to request more heap memory

Nexus S (4.2.1): normal, Largeheap 512

4. If an attempt to request more memory than the current remaining heap memory will cause outofmemoryerror ()

5, application due to all aspects of restrictions, need to pay attention to reduce memory footprint, avoid memory leaks.

Use the Mat tool to detect memory leaks

Creating a new memory analysis in an attempt window appears with a


No, you can go to http://www.eclipse.org/mat/downloads.php to install mat

Ddms in the Android debugging environment, find heap Dump



A mirrored file in the current memory under Dump, *****.hprof


You can clearly see the size of the memory for each part.

You can also switch attempts, and group to see the details of different classes of different packages.


Heap Dump

? Contains a memory snapshot of the Java process at the moment that triggers the heap dump generation, with the main contents of each Java class and object allocated in heap memory

Memory Analyzer Tool (MAT)


Common Memory leak reasons

Context Object leak

1. If a class holds a strong reference to a context object, it needs to check whether its life cycle is longer than the context object. Otherwise, a context leak may occur.

2. View holds a reference to the context object it creates, which can cause a memory leak if the view object is passed to a strong reference that is longer than the context in which the view is located.

For example, View#settag (int, Object) memory leak https://code.google.com/p/android/issues/detail?id=18273

3. Assign the context object to the static variable.

Avoid context object leaks checklist

1, check all the objects that hold the strong reference to the context object life cycle is beyond the lifetime of the context object it holds.

2. Check to see if there is a view outside the context of the view, if you need to check the life cycle.

3, the tool class is best not to have the context member variables, as far as possible in the call function directly passed through the call parameters. If you have to have a context member variable, consider using WeakReference to refer to it.

4. View holds a reference to the context object it creates, which can cause a memory leak if the view object is passed to a strong reference that is longer than the context in which the view is located.

5, check the context or view object assigned to static variables where to see if there is a context leak.

6, check all put the view into the container class place (especially static container class) to see if there is a memory leak. 7, use Weakhashmap also need to pay attention to have no value-key reference.

7, try to use ApplicationContext.

Handler Object leaks

1. Messages sent to handler are actually added to the main thread's message queue for processing, each holding a strong reference to its target handler.

As we normally use the anonymous inner class handler


Handlermhandler = new Handler () {
@Override
Public Voidhandlemessage (msg) {
Mimageview.setimagebitmap (MBITMAP);
}
}


The above is a simple use of handler. When an inner class (including an anonymous class) is used to create a handler, the handler object implicitly holds a reference to an external class object (usually an activity) because the view is attached to an activity. Handler is usually accompanied by a time-consuming background thread (such as pulling pictures from the network), which notifies the handler through the message mechanism after the task finishes (for example, when the picture is downloaded), and then handler updates the picture to the interface. However, if the user shuts down the activity during the network request, and normally the activity is no longer used, it is likely to be reclaimed at the GC check, but because the thread has not finished executing and the thread holds the Handler reference (otherwise how does it send a message to Handler?) , the handler also holds references to activity, which causes the activity to be recycled (i.e., memory leaks) until the end of the network request (for example, the picture is downloaded). In addition, if you execute the handler postdelayed () method, the method loads your handler into a message and pushes it into the MessageQueue, before the delay you set up arrives, There will be a chain of MessageQueue-> message-> Handler-> activity that causes your activity to be held in a reference and cannot be recycled.

Of course, for the reason that handler holds references externally, we can set the activity as a weak reference and no longer execute the internal method when it is unnecessary.



/**
* @author Zhoushengtao
* @since 2013-12-16 3:25:36
*/

Import android.app.Activity;
Importandroid.content.Context;
Importandroid.os.Handler;
Importandroid.os.Message;

Importjava.lang.ref.WeakReference;

Publicclass Weakrefhandler extends Handler
{
Weakreference<context> Mweakcontext;

Public Weakrefhandler
{
Mweakcontext = newweakreference<context> (context);
}

@Override
public void Handlemessage (msg)
{
if ((Mweakcontext.get () instanceofactivity) && ((activity) mweakcontext.get ()). Isfinishing ())
return;
if (mweakcontext==null) {
return;
}
Super.handlemessage (msg);
}
}


2, Non-staticinner class and anonymous class hold a reference to their outer class.


Memory leaks caused by drawable.callback

The Drawable object holds a drawable.callback reference. When a Drawable object is set to a view, the Drawable object holds the view reference as Drawable.callback


Avoid drawable.callback causing memory leaks

? Try not to save the Drawable object in a static member

? For drawable objects that need to be saved, call Drawable#setcallback (null) when needed.


Other memory leaks #65533; " http://www.2cto.com/kf/ware/vc/"target=" _blank "class= keylink" >vc3ryb25npjwvcd4kphagywxpz249 "left" > 1, Memory leaks caused by Android DigitalClock http://code.google.com/p/android/issues/detail?id=17015

2, using the Map container class, as a key class does not correctly implement hashcode and equal functions

Other memory leaks

? Memory leaks in JNI programs

1, Malloc/free.

2. JNI Global Reference

? Thread-local Variable

1, equivalent to the thread of the member variable, you can store threads-related state

2, if thread is alive state, then the object in Thread-local can not be GC.

Process Memory footprint Monitoring Tool

Dumpsys

? $ Dumpsys meminfo [PID]


Procrank + Shell Script

? #procrank

1. vss-virtual Set Size Virtual consumption memory (contains memory occupied by shared libraries)

2. Rss-resident Set Size actually uses physical memory (contains memory occupied by shared libraries)

3. pss-proportional Set Size actual physical memory used (proportional allocation of memory occupied by shared library)

4. Uss-unique the Set Size process takes up physical memory alone (does not contain memory occupied by shared libraries)


Shell Script

#!/bin/bash

While true; Todo

Adbshell Procrank "grep" Com.qihoo360.mobilesafe "

Sleep1

Done


Of course, some models of SH are through Third-party mobile phone business streamlined, a lot of orders are not used. Procrank is a command that is often trimmed down.

In view of this:

Wrote a small tool to detect real-time changes in memory,

GitHub Address: Https://github.com/stchou/JasonTest



Summary

1. Think twice before saving objects

I. There is no implied reference to the object itself

Ii. when can be recycled after preservation

2. To understand common implied references

I. Anonymous class outer class

Ii. View to context

3. To check the memory footprint with exceptions through various tools

4. When creating a large object, check its lifecycle


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.