Performance Optimization for Android and Android

Source: Internet
Author: User
Tags try catch

Performance Optimization for Android and Android


Performance optimization is a major category. If someone asks you how to optimize performance in Android, you may not know where to start.

The first thing we need to understand is why our App needs to be optimized. The most obvious time is that the user says, what shit, and the brush hasn't responded for so long. Just take the off and uninstall it.

This has something to do with it. Let's refute it pale first. Nima's old network and equipment are bad. It's off my ass and there's no need to optimize it. However, the boss shot the board and put pressure on the CTO. Then the CTO came to you again: Today, Y must be optimized for me, or I will not go home.

Well, why is the App slow and messy in terms of the UI. Let's try to analyze it.

Off-topic: Change minSDK to 4.0 +. The low users who go to theme are reluctant to change their mobile phones. Can you count on how much revenue it can bring to you? Just pass it off. There are a lot of System bugs before 4.0, and the overall high performance cannot be reduced to make up for these bugs.

Let's start with the UI:

The first thing to understand is the UI rendering process:Measure-layout-draw, Both measure and layout require all the child controls of the for loop to complete the painting and layout. Therefore, the more child controls, the longer the time consumed (Inflate, layout_weight, relative, multi-layer nestingTo reduce unnecessary child controls or hierarchies. You can use the merge and viewstub labels to reduce hierarchical nesting. If your concept of space is not that good, you can use HierarchyViewer to check.

For a multi-item component such as Listview or GridView, reusing items can reduce the number of inflate times and achieve reuse through the ViewHolder method of setTag and getTag. Note that, the control in holder should be reset before value assignment to avoid image and text disorder.

When ViewPager is displayed for the first time, there are several optimization methods:

    • It is best to set the number of pages cached by ViewPager to a minimum value of 3 at the same time. If there are too many pages, there will be a lot of pager initialized by ViewPager during the first display, so that the accumulated rendering time of pager will increase and it looks like a card.

    • Each pager should load the network or database only when it is displayed (UserVisibleHint = true). It is best not to pre-load the data to avoid waste.

What should I do if the image cannot be displayed or the loading time is too long? Divided into two parts,Download speed and loading speed.

    • For downloading, you need to control the maximum number of tasks to be downloaded at the same time (the average speed is slow), and adding a buffer stream to InputStream will be faster (such as BufferedInputStream ).

    • For the loading speed, we need to know that although the downloaded image may only be several hundred kb, the memory occupied by bitmap is multiplied, and minimizing the image size is the fundamental factor, it is the best solution to let the server provide images with different resolutions. The memory is always exhausted. Don't always think that the large resolution will be clearer, and the actual space is only 150*150, it is inappropriate to get a 1000*1000 image. In addition, the loading speed: Memory> hard disk> network, reasonable use of memory cache is also the key. If you do not write well, it doesn't matter. There are so many open-source image cache frameworks that you don't have to worry about.

Besides Cache

There are many caching methods, and we don't need to list them using Stay. What we want to talk about is to use them together.

    • For example, we used to use strong references, HashMap, and later we found that the memory occupied, we used soft references, and weak references for timely recovery. Later, the recycling mechanism was uncontrollable, with lrucache, disklrucache uses algorithms to balance the memory and hard disk cache. With the development and evolution of android, we should also embrace changes. If your App has soft references and weak references, check them again.
    • For example, network + database. We generally take the initiative to obtain the network, rather than passively accept it. What if the data is repeated or unchanged? So what is the significance of retrieving network data? My solution is to set a maximum request interval for each activity, fragment, or component, such as a listview. When requesting data for the first time, save a copy to the database and write down the timestamp, when the next re-Initialization is performed, determine whether the maximum time interval is exceeded (for example, 5 minutes). If no, only the database data is loaded and no network request is required. Of course, some implicit http request frameworks will cache server data and no longer request the network for a certain period of time, or directly return the previously cached data when the server returns 304.

We also talk about the network.

    • Now there are many ready-made HTTP frameworks for us to use. We can handle a url request with almost only the write configuration, but there are many services that need to be used together, such as the json data format, in place of jpg, WebP supports resumable data transfer. Multiple requests are merged into one with no redirection, server cache, and Server Load balancer.

    • For the client itself, in addition to the above implementation, we also need to properly cache, control the maximum number of concurrent requests, promptly cancel invalid requests, filter duplicate requests, and set the timeout time, request priority settings.

Optimization is not a human task. It is easy to implement a simple function, but it is difficult to optimize reconstruction. Multi-faceted pre-judgment and joint debugging are required. Reasonable assumptions and practices are the most important means of optimization.

After talking about these specific points, let's talk about some common sense or code specifications.

    • You need to know that do not declare temporary variables in the for loop. Do not write try catch in the for loop.

    • Understand the garbage collection mechanism to avoid frequent GC and Memory leakage. OOM)
    • Rational use of data types, such as StringBuilder instead of String (str + = "str" is the most common example in the pen test). Use less enum and less parent class declaration (List, Map)

    • If you have frequent new threads, execute them through the thread pool to reduce thread creation overhead.

    • You need to know the benefits of a singleton and use it correctly.

    • Use multiple constants, use less explicit "action_key", and maintain a constant class. Do not declare these constants again.

    • If you can, at least understand the policy patterns, combination patterns, decoration patterns, factory patterns, and observer patterns in the design patterns, which can help you properly decouple, even if demand changes frequently, you don't have to worry about getting started. The requirement change is not terrible. What is terrible is that there is no reasonable design before writing the code.

Of course there are many other things. Stay is just a big outline, and you still need to keep trying it on your own. There is a big difference between developing and writing code and making products. It's just a matter of attitude that we can beat 80% of coders. When you come across some areas that require optimization and analyze with patience, the accumulation of time will make you a real engineer.

In addition, the optimization is not absolutely perfect, and every optimization is based on the current environment. We need to understand that communication is the best optimization, and we should think twice without going blindly.

On Android, how does one optimize performance? It takes about three years to write code.

 

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.