On the optimization of app performance

Source: Internet
Author: User

Objective

Some time ago, the company's small partners on the app performance optimization technology sharing. Here I tidy up a little bit and share it with you. The topic of performance optimization is very large, and the coverage can be very broad and very deep. My ability is limited, will not give you particularly difficult to understand, especially the bottom of things. Are the points we develop that we can start to do. Everyone is talking about performance optimization, but it's hard to have a concept for a friend who is not very experienced with the project. When doing optimization will be more vacant, here I will show you the direction.

Where to start?

When I do product development, I also encounter performance bottlenecks. Test Project Teacher Feedback Some of the more obvious problems, such as the UI of the excessive drawing, the list of sliding obvious lag, compared to the memory, and so on, but the past is not targeted to do the corresponding optimization, so by ensuring product quality of the starting point, oneself set the relevant performance optimization program, may not be too mature. Just can be gradually intact. and find the most suitable for their own product optimization program.

Here I have set four directions:
-Response times (Response time)
-Interface Lag (ANR)
-Memory consumption
-Memory leaks (out of memories)

Response time

This refers to the client and server interaction, to get the data, parsing, and then display to the interface of the whole process of time spent.

This section deals with the optimization of the client. Also involves server-side optimizations, where only the client is discussed.

HTTP request mode

Our app is generally inseparable from the network, the request interface is the most common operation, how to request, what we will be in the initial development of the set, the service to my provided interface, can be roughly through get, POST, HEAD, PUT, delete these kinds of request way, Different request methods have different application scenarios, such as GET requests. Should be used to request a return result. The number of references is part of the URL, and the POST request. Used to request changes to server-side data or status. The head request is the same as get. Only the server cannot return the message body in the response; Put requests are used to place the page in the correct location; Delete requests are used to remove the server-specified document.

Using an excellent open source HTTP framework is a good choice for us. Its advantage is through the market verification, very many pits have been filled, the disadvantage is that we need to delve into its ability to expand it. It's not always possible to fill a hole.

Suppose you build a wheel. It also requires us to take the time to verify and adapt to our business needs, but the advantage is that we are able to expand the controls ourselves, but this is very much about the quality of the developers.

Data parsing

The actual development of the service side of the return data format is nothing more than two kinds:
-JSON
-XML

Both format data formats have pros and cons. From the readability point of view, XML is slightly better, but JSON also has a canonical label, from the resolution of the difficulty and speed, we are more inclined to use JSON, now JSON is the mainstream data format.

In Android we can use excellent analytic library to speed up our parsing speed, there are Dom4j,json in XML, Jackson, Gson. We use these libraries to achieve faster data resolution and improve our development efficiency.

Data storage

The previous section is about data parsing. After we parse the data, we may need to store the data somewhere, five ways to store Android:
-Content Provider (used primarily to share data with other applications)
-SQLite (store data in the database)
-File (save local files)
-Sharedpreference (mainly used to save simple configuration information)
-Networked storage (WebService data returned or parsing HTTP protocol for network data interaction)

In order to improve the response time of the application, the data cache is a better way, we can preprocess the data returned by the server and cache the data for refresh.

Optimization points:
-Asynchronous request for network data
-Preprocessing server return data
-Asynchronous data store operations
-Data Cache Refresh
-Timeout retry
-Manipulate the UI in the main thread

Interface Lag

ANR says "application is unresponsive" and this is what we need to avoid, the cause of this anomaly:
-The main thread ("Event processing Thread"/"UI thread") did not respond to input events within 5 seconds
-Broadcastreceiver not run in 10 seconds

There are many reasons for ANR, and the common scenario is that it takes time-consuming actions on the UI thread, such as "network requests" and database operations.

So how to avoid it?
-The UI thread simply refreshes the interface and does nothing, regardless of the time-consuming operation. Time-consuming operations are placed on child threads to do
-Ability to use Thread+handle or asynctask for logical processing

Memory consumption

The memory of each cell phone is limited, and the memory we refer to here refers to the cell phone's RAM, which is the abbreviation for Ramdom Access memory. There is ram in the data that our application needs to read and write randomly, and the Android phone consumes memory. This is related to the processing of the Android backend, and we know that Android apps are developed using Java. Running Java requires a virtual machine, which means that every app you open creates a virtual machine. This requires memory, so the more applications we open, the more background processes. Memory is allocated, which results in a serious memory consumption.

In fact, we don't have to break the problem, just enough memory. Our app is still a card. The application we develop relies on the heap memory allocated to us by the system, the general upper limit in 16m~48m, but we can apply many other heap memory by androidmanifest setting the Application property largeheap= "true".

Get the available heap memory limit by using the following code:

mActivityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); mMaxMemory = mActivityManager.getMemoryClass();
Memory leaks

Memory leaks The problem has been said to be rotten. We all know that there is a memory leak, but why is there a memory leak?

The memory leaks here are not the true meaning of leaks. Instead, there is not enough memory to perform GC operations, which can lead to excessive memory consumption. Throws an out of memory exception and is killed by the system.

JVM recovery mechanism

It's time to talk about the recovery mechanism of the JVM. See:

The JVM manages three generations of Java objects. The younger generation, the old generation, the permanent generation, respectively.
Young Generation: The vast majority of Java objects are allocated in younger generations and are recycled in younger generations.
Old Generation: In the young generation, long-term existence of non-recycled Java objects will be transferred to the old generation, this heap space will generally be larger than the younger generation of heap space.


Permanent generation: Stores metadata for VMS and Java classes. As well as interned strings and static variables of the class.

This involves the knowledge of the JVM, which is not further explored here.

But we should be able to understand the role of the garbage collector:
-Allocating memory
-Ensure that all the objects being referenced still exist in memory
-Reclaim memory for objects that are no longer referenced by the running code

Object reference

The reference types of Java can be divided into the following categories:
-strong reference (strong Ref): Strong, remove the strong can be, will be recycled.


-Soft Reference (Soft Ref): sufficient memory. Keep, memory is tight. Is recycled and is used primarily for caching.
-Weak references (Weak ref): Weaker than soft ref, and can be recycled even if memory is not tight.


-Virtual Reference (Phantom Ref): Does not persist in memory for whatever object.

A picture wins thousands of words:

Use strong Ref to store large amounts of data. Until the heap burst, the perm Gen burst with inter strings (or class loader loaded into a large number of classes), then the memory leaks.

How to optimize?

In front of some background knowledge, we understand the memory optimization has some help, the following is a brief talk about the direction of our optimization:
-Layout optimization
-Memory optimization

Layout optimization

You can come up with your Android machine.
Developer Tools-profile GPU rendering-Choose to display a bar chart on the screen

-Blue represents the time to measure the display list
-Red indicates the time required for OpenGL to render the display list
-Yellow represents the time the CPU waits for GPU processing
-The middle green horizontal line represents vsync time 16ms. Try to keep all the bar charts under the Green Line.

Why is 16ms?

The Android notification interface renders and redraws the time to complete within 16ms. Assuming more than 16ms, it will result in dropped frames, which is what we often say the lag.

Optimization points:
-Avoid Overdraw
-Optimize layout levels
-Avoid too many useless nesting
- <include> reuse Layout with tags
-Use <ViewStub> delayed loading
-Hierarchy View for hierarchical analysis

The detailed usage, here does not introduce, does not understand on Baidu.

Memory optimized

Memory-optimized points there are very many, here I mainly divided into two chunks:
-Bitmap optimization
-Code optimization

Bitmap optimization
    1. Pictures with the right resolution and size
    2. Timely recovery of memory (Bitmap.recycle ())
    3. Use picture caching (LRUCache and Disklrucache)

1th, it is shown on demand. For example, in the list of pictures, you can display thumbnails, details page, you can load the corresponding resolution of the picture. This reduces memory consumption and generally requires the server to provide images of multiple resolutions.

2nd. Bitmap is very memory-intensive, especially in the larger bitmap, can think of optimization is the use of recall, bitmap compression, using Bitmapfactory.options settings insamplesize can reduce the image.

3rd. Image caching, this can be used in a mature picture frame, such as Universal-imageloader, Fresco, Picasso, these frames are very good image optimization, we can control, choose to use it.

Code optimization

About the code this has said, no matter what can improve our program optimization point can be written here, there is no way to put all the optimization points listed here, only to provide relevant references, the rest of the experience to summarize and accumulate.

Optimization points:
-Use the static modifier for constants
-Using static methods
-Reduce unnecessary member variables
-Try not to use enumerations. Use less iterators
-Objects such as cursor, Receiver, Sensor, file, and so on. Be aware of their creation, recycling and registration, and counter-registration
-Avoid extensive use of annotations, reflections
-Use Renderscript, OpenGL for complex drawing operations
-Use Surfaceview to replace view for large, frequent drawing operations
-Use view caching as much as possible instead of running the inflate () method to parse the view every time

Note: The relevant optimization points for Android elite are referenced here

    • Additional memory space is required to create new objects. To minimize the creation of new objects.
    • Change the visibility of classes, variables, methods, and so on to a minimum.
    • For concatenation of strings, use StringBuffer instead of string.
    • Do not declare a temporary variable in the loop, do not catch the exception in the loop.

    • Assume that there is no requirement for thread safety, try to use a thread-unsafe collection object.
    • Use the collection object, assuming you know its size beforehand. You can set the initial size in the construction method.

    • The file read operation requires the use of a cache class. Close the file in a timely manner.
    • Caution with exceptions, using exceptions can cause performance degradation.
    • Assuming that the program creates threads frequently, you can consider using a thread pool.

The above are some of the experience summary, roughly all the same, friends in the code optimization. Can be based on these optimization points, targeted to refactor code, in fact, the most important is the readability of the code, the structure is clear.

Performance optimization Tools
    • Memory Monitor-RAM monitoring tool
    • TraceView
    • MAT

Android developers must be familiar with several of the above performance tuning tools. Here I don't write so much nonsense, about their usage, the official website of other Daniel's blog has been introduced.

At last

The starting point for writing this article is also a clearer understanding of the Android performance optimization, no matter what things can not be done overnight, it is necessary to follow the progressive, for a person who has just started learning you talk about optimization is very unrealistic. We first to do a good job, and then to consider the corresponding optimization, the author is constantly learning among them. Improve the quality of the product by drawing on other's good optimization scheme. Thank you for your interest in the author.

On the optimization of app performance

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.