Performance optimization is a big category, and if someone asks you how to do performance optimization in Android, you probably don't know where to start.
The first thing to understand is why our app needs to be optimized, the most obvious moment: User say, what dog excrement, brush so long did not respond, take off uninstall forget.
This is related to what, we first pale rebuttal, the user equipment old net and rotten, shut my fart thing, do not need optimization. However, the boss of the decision, pressure to the CTO, and then the CTO came to you: Y today must give me a way to optimize, or not allowed to go home.
Well, why is it that the app's card is slow and chaotic from the perspective of the UI. Let's try to dissect it.
Digression: Change the MINSDK to 4.0 +, to special low users, even mobile phones are not willing to change, but also can expect it to bring you how much revenue, directly pass out. There are many system bugs before 4.0, which can not reduce the overall performance in order to compensate for these bugs.
Okay, let's start with the UI:
The first thing to understand is the UI drawing process :measure-layout-draw, measure and layout all need a For loop all the child controls, together to complete the drawing, layout. So the more child controls, the longer it takes (inflate,layout_weight,relative, multi-layered nesting , and so on) to reduce unnecessary sub-controls or levels, which is quite necessary. You can reduce hierarchy nesting by merge,viewstub these tags. If your space concept is not that good, you can use the Hierarchyviewer tool to check it.
For a ListView or GridView multi-item component, reusing item can reduce the number of inflate times and be reused through the Settag,gettag viewholder approach, and it is important to note that the controls in Holder are best Reset and then assign value, to avoid the picture, text confusion.
For the first display of the Viewpager and left and right sliding lag, there are several ways to optimize:
-
-
Viewpager at the same time cache page number is the best minimum 3, if too many, then the first display, Viewpager will initialize a lot of pager, so pager cumulative rendering time will increase, it looks like card.
-
Each pager should only load the network or database (Uservisiblehint=true) when it is displayed, and it is best not to preload the data to avoid wasting
What if the picture doesn't show up or the load time is too long? It is divided into two parts, download speed, loading speed .
-
-
For download, control the maximum number of simultaneous downloads (slow average) while inputstream a layer of buffer flows faster (e.g. Bufferedinputstream).
-
For loading speed, we need to know that although the downloaded image may be only hundreds of K, but decode into bitmap occupied by the memory is multiplied, as far as possible to reduce the size of the picture is the fundamental factor, so that the service side to provide different resolutions of the picture is the best solution, memory is always exhausted time, Don't always think about the large resolution will be clearer, the actual only 150*150 space, not to get a picture of 1000*1000 is inappropriate. In addition, load 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 picture caching framework, do not worry about themselves.
Again cache
There are a lot of ways to cache, and do not stay enumerated, we have to say is used in conjunction.
-
- For example, we have been using strong references, HashMap, later we found that accounted for memory, we use soft references, weak references to timely recovery, and later because the recycling mechanism is not controllable, so there is a lrucache,disklrucache through the algorithm to balance memory and hard disk cache. As the Android version progresses and evolves, we should embrace change as well. If you have soft references and weak references in your app, check again.
- Let's say Network + database. Network we are generally to take the initiative to obtain, rather than passive acceptance. What if the data is repetitive or unchanged? So what's the point of going to fetch the Internet data? My solution is to set a maximum request interval for each activity or fragment or each component, such as a ListView, save a copy to the database the first time the data is requested, and note the timestamp, and when the next reinitialization is over, determine whether the maximum time interval (such as 5 minutes) is exceeded. If not, only the database data is loaded and no network requests need to be made. Of course, there are also implicit HTTP request frameworks that cache server data, no longer request the network for a certain amount of time, or return the previously cached data directly when the server returns 304.
Anyway, when it comes to the internet, we also say
-
-
Now there are a lot of out-of-the-box HTTP framework for us to use, we almost only write configuration can take a URL request, but there are a lot of service-side matching, such as: JSON data format, WEBP instead of JPG, support breakpoint continuation, multiple requests merged into one, try not to redirect, Server caching, load balancing, and more.
-
To the client itself, in addition to the above implementation, we also need a reasonable cache, control the maximum request concurrency, timely cancellation of expired requests, filtering duplicate requests, timeout time settings, request priority settings and so on.
Optimization is not a person's business, to achieve a simple function, but to optimize the refactoring, it is not easy. Many aspects of pre-judgment and joint adjustment are required. Reasonable assumptions and practices are the most important means of optimization.
To finish these specific points, let's talk about some common sense, or code specifications.
-
You need to know that the For loop does not declare a temporary variable, and it is not the last resort to write a try catch.
-
reasonable use of data types, such as StringBuilder instead of string, (the most common of the written questions is str+= "str" There are several objects in it, less enum enum, less parent class declaration (List,map)
-
If you have frequent new threads, It's best to execute them through the thread pool, reducing the thread creation overhead.
-
-
multi-use constants, less explicit "Action_key", and maintain a constant class, and do not repeatedly declare these constants.
-
If you can, at least understand the design pattern of the strategy mode, combination mode, decoration mode, Factory mode, observer mode, which can help you to properly decouple, Even if your needs change frequently, you don't have to be afraid of reaching. The need to change is not scary, and the scary thing is that there is no reasonable design before writing the code.
Of course there are many, stay said is only a large outline, or need to keep trying. will develop write code and will do product differences or pretty big, just attitude can brush dead 80% yards of farmers. When you come across something that needs to be optimized, be patient and analyze, and the accumulation of time will make you a real engineer.
In addition, optimization is not absolutely perfect, each optimization is based on the current environment to do, to understand that communication is the best optimization, not blindly follow, not casually, think twice before the line.
How does performance optimization work on Android? About three years of code will be almost known.
Those performance optimizations in Android