Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

Our attitude is: a little progress every day, the ideal will eventually be realized.

In addition to an app to have amazing features and interaction beyond outrageous, the performance should also pursue silky requirements, so as to better improve the user experience.


The following are my work in a number of summary performance optimization of experienced, according to the roadmap of the story, which is divided into five parts , namely: common performance problems ; some of the possible causes of performance problems; solve performance problems routine; code for proposals and potential performance troubleshooting items.

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

As see FIG large, there will be hereinafter dismantling

A First, let's look at what are the performance issues

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

1, a memory leak.

Popular terms, memory leaks will not only cause the application memory footprint is too large, would cause the application Caton, resulting in poor user experience, as to why a "small" memory leaks can cause application Caton, I had to take this picture is talking.

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

  • Yes, this is Android developers need to understand the shoes of Generational Heap Memory model, here we are only concerned when the object is alive for some time after the Young Generation, if not to be killed, it will be moved to the Old Generation in the same way, finally It will move to the Permanent Generation.
  • So think on their feet to know if a memory leak, then, sorry, you piece of memory over time will naturally into the Permanent Generation, the natural goose, memory is not a cabbage, you want to have as many here, because the sand the reason box mechanism, memory allocated to your applications so of course there is a limit, you can not go beyond (someone laugh, not a large heap Why, of course I laughed, I do not see this cargo is android guru players of all ages too)
  • Well, the object of your piece of memory leaks caused by dog ​​in the manger, and the rest can be used for other objects to play memory space is less; analogy, a small stage, actors take to the stage performances, there is no extra space, he other actors can only wait for him to show off ah, this waiting time is not continuous performances, so the card thing.

2, frequent GC

Oh, GC frequent cause Caton, you must go through the baptism of the above, already we know why, yes, of course, but also because of "lack of stage space, new actors performing on stage need to let the show finished down." So what causes this phenomenon is it?

a, memory leaks, well, you know, do not say, this must be possible cause.

b, a short time a large number of objects are created, they "need" to be released in a short time, attention to the needs here, in fact, have to, why, again due to "lack of stage space", for example, new in the onDraw object because onDraw about 16ms will perform a (wait, you can determine, what is about 16ms, I'm sorry, can not, the frame is not lost, even out a little bit).

Brain mend, create about 60 objects per second, ah, Sao years, do you think Young Generation cabbage what, how many took much want to take, I'm sorry, where is the limit, here run out in to apply, I have to go back to recover some, I gotta recover it time-consuming, time-consuming, well, onDraw waiting, waiting're missing out on next execution of 16ms, and if so, the user looks up the card.

3, power consumption issues

There is a very acute problem, that is a microscopic look at the video to see a small phone will be hot, so power users have been very concerned about the problem km, but I am sorry that our app has not encountered serious power consumption problem, although not encountered serious problems of power, does not mean you do not need to know the solution to this problem, I have summed up:

a, there is nothing particularly important information, for example, the money credited into account, phone, and 100 yuan no threshold real deal voucher method, etc., please do not bother users, users do not wake up frequently, otherwise, the result can only be unloaded, or turn off all notifications.

b, do the appropriate local cache to avoid frequently requested data network, here, is easier said than done is not able to get the ax Mito two, with a good caching strategy to distinguish between what is a period of time will not change, which is absolutely not cache is important.

c, for some time longer perform synchronization operations in the user charge and there is wifi in the time to do, unless you force synchronization .. and so on, do not pull too much, because there is still a lot of content.

4, OOM problem

Oh, this, presumably after the previous 1,2 baptism, you should already know what causes this, you can think about, "an actor on stage will be a huge fat man, even if the actors do not show down he is also not make it up, how to do, I make a failure, but also how to do, direct crash, finish! "the cause of the problem, there may be, (Oh, sure, could only say, from the time of analysis here departure)
a, memory leaks, and presumably you smile.

b, a large number of invisible objects occupy memory, this is actually very common, but we may have been too concerned about nothing, such as request interface returns the list has 100 data, each data such as there are 100 fields, where you show users only a few of the 10 data only, however, when you parse the remaining 99 unknowingly eating up your memory, when, due to memory when there is a fat man, Oh, belch fart.

c, there is a very common scenario is a diagram of a multi-page scene, obviously each figure only need to load a 100_100, but you use the original size (1080_1980) or more, and all of a sudden you also loaded a few dozen sheets , What Can Go? So look inSampleSize, or, if you upload pictures owned by management, you can use Vientiane excellent map, he made a good cut different sizes of pictures for you, so you do save on the client side image scaling up.

More than two-understand some performance issues, here, a simple string a bunch of reasons causing these performance issues

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

1, man-made slight time-consuming operation ui thread, resulting ui thread Caton

Ah, many small partners disagree, that read in onCreate what pref count, what of resolve under json data, the actual situation is not the case, the correct approach is to encapsulate these operations using asynchronous, small partners can look rxjava, and now the latest version is already rxjava2, if use is not clear, you can Google it.

2, layout is too complex to be completed in 16ms rendering

  • The many small partners fully understood, here under the simple understanding, we briefly put rendering roughly divided into "layout", "measure" "draw" several stages so, of course, you do not actually think that is true, good, level of complexity, layout, measure might use the time should not be used, naturally, left to draw the time may not be enough, and naturally on the tragedy.

  • So many of the recommendations previously given that the use of RelativeLayout replace LinearLayout, and it can reduce the layout level, however goose, now please do not recommend others to use RelativeLayout, because ConstraintLayout is a higher performance level layout eliminate artifact.

  • ConstraintLayout Cassowary based algorithm, while the advantage is that there Cassowary algorithm is extremely efficient when solving linear equations, it turns out, linear equations is very suitable parameter for defining user interface elements. Because people graphics sensitivity is very high, so the UI rendering speed is very important.

  • So in 2016, iOS and Android are based on Cassowary algorithms to develop the layout of the system of their own, here are ConstraintLayout with the traditional layout RelativeLayout, performance comparison when LinearLayout achieve, but here are foreigners test data, the original can be found here. demo also provides a method of testing, of interest to a small partner can try slightly.

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

Measuring / layout (Unit: ms, the average value of 100)

3, too much animation at the same time to perform, leading to overload CPU or GPU

This is mainly because the animation usually frequently change the properties view, leading displayList failure, and need to re-create a new displayList, if too much animation, this overhead can imagine, if you want to see a more detailed look at this recommendation slightly, there knowledge in section 5.

4, view overdraw problem.

  • View overdraw problem can be said to be one of the most common problems we encounter when writing layout, can be said to be writing an inattentive to write a overdraw, usually it occurs in a nested viewgroup , such as you gave him a set of unnecessary background.
  • Troubleshoot problems in this area is not too difficult, we can set the inside of the developer options via phone, open the Show GPU Overdraw options easily find these problems, and then try to close the blue.

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

5, the problem of excessive gc, not here in the repeat of the above have been in a very straightforward.

6, leading to the slow implementation of resource loading.

Do not load sometimes avoid some of the resources, there are two solutions the way, the scene is not the same use.
a, pre-load, that is not yet come before the path, it is well ahead of time to load, eh, it seems that Jiang Zi oh x5 kernel.

b, it is used to wait until loading, please give a progress bar, do not let users wait for dry, do not know when to stop and cause a bad user experience.

7, the worker thread priority settings wrong, lead and seize the ui thread cpu time.

Use Rxjava junior partner to pay attention to this point, execution threads set up a task you might have a greater impact on performance, without the use of a small partner can not be too careless.

8, static variables.

Hey, everyone must have had to set a static variable in the application of experience, way back when, in order to cross the pit 1M Intent can only pass the following data, I set up a static variable in the application for the two activity "transfer (shared) data ", however, step by careful data, with the tail of the previous activity, and therefore leaked. Not only is such an example, just a few:

a, you use a static collection of saved data, right?

b, Manger certain single cases, such as management AudioManger encountered it?

Three analyze problems encountered since also been, then the next, naturally, is how to use a sword stick swords and clubs to solve these problems

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

1, GPU overdraw, positioned over the drawing region

Here directly on the developer options, open the Show GPU Overdraw, you can see the effect easily find the piece needs to be optimized, then the specific how to optimize:

a, reduction layout level, above mentioned, using ConstraintLayout replace traditional layout. If you ConstraintLayout do not know, it does not matter, this article teaches you 15 minutes to learn how to use ConstraintLayout.

b, check if there is excess background color, we usually make some stupid mistake - the parent view to set the background to be covered, in most cases these backgrounds are not necessary.

2, the main thread time-consuming operation investigation.

a, open strictmode, this way, time-consuming operation are the main thread will be presented in the form of warning to logcat them.

b, plus direct object of suspicion @DebugLog, view time-consuming method. DebugLog notes the need to introduce plug-hugo, this is an early work Android God JakeWharton, for the execution time monitoring function is very convenient, add comments directly on the function can be achieved, but there is a drawback is that the last version JakeWharton released without the support of release alternative methods to monitor version with an empty code, so I posted here a maven to the company's warehouse, citing the official website of way and similar, but the address is: 'com.tencent.tip: hugo-plugin: 2.0.0-SNAPSHOT '.

3, for the measure, layout consuming too much of a problem

Generally such problems are too complex reasons superior layout results in, because now there are ConstraintLayout, it is strongly recommended to use ConstraintLayout reduce layout level, the general problem is solved, if we find there is a performance problem, you can use traceView observe time-consuming method to The concrete causes lower.

4、leakcany

This is the silver bullet memory leak monitoring, we should have used, need to remind that, pay attention to:

dependencies {

debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'

releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'

}

The introduction of the way, releaseImplementation monitoring to ensure the removal code release package, otherwise, he kept the self-generated catch memory snapshot, itself also affect performance.

5, onDraw write code which needs attention

onDraw better than probably every 16ms will be executed once, itself equivalent to a forloop, if you are inside the new object, then unknowingly meet a large number of objects created and released a short time, so frequently GC occurred, ah, shake the memory, so the card. Therefore, the correct approach is to put out new objects out.

6, json deserialization problem

deserialization json refers to json string into an object, if there are more than data, in particular, a considerable number of string when parsing them not only time consuming, but is still eating memory. Solution to this is:

a, streamlining field, in consultation with the background, the relevant interfaces eliminate unnecessary fields. To ensure that the principle of minimum available.

b, using flow analysis, before I considered json analytic optimization, search to this on Stack Overflow. So we can understand that this is Gson.fromJson play, can improve resolution efficiency of 25%.

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

7, viewStub & merge use.

Here merge and viewStub presumably everyone is well aware of the layout of the two components, and for components only under certain conditions show up, it is recommended to use viewStub wrapped up, the same way, include a layout if its layout and the introduction of his roots father consistent layout, we recommend using merge wrapped up, if you are worried about the effect preview issue, there is no need, because you can

tools: showIn = "" property, so you can preview the normal display.

8, load optimization

Here and not too many technical points on the inside, nothing more than a time-consuming operation to the asynchronous packages go, but one thing I must mention is, pay attention to the problem of multi-process, if your application is multi-process, you should realize oncreate method your application will be executed multiple times, you will not want to load the resources it many times, so you just loaded in the main process, the case appeared in some pit, there are other processes may require that certain parts of the resource then he does not lack the process to load the appropriate resource, then belch fart.

9, refresh optimization.

This point in the previous article I have mentioned, here are two examples of it.

a, for operating item in the list, such as thumbs up for the item, then should not the whole list refresh, but it should only refresh this item, compared to skillfully use recyclerView you should know how to operate, do not understand look here, you will understand what recyclerView the partial refresh.

b, for the more complex pages, personal recommendations do not write in an activity, it is recommended to use several fragment assembled, so to change the module can be refreshed only one specific fragment, rather than the entire page refresh logic are gone. But the question is, how to share data between a fragment of it? Well, look at how I operate.

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

  • Activity data abstracted as a part of this LiveData, LiveDataManger pay a management data, and then get through this context the respective Fragment Activity from the LiveDataManger LiveData, operation, activity data change notification and the like.
  • Haha, you read right, and this is indeed a bit like Google that LiveData, of course, that if you want to use Google's naturally no problem, but this is a simplified version. The introduction of the project
  • 'com.tencent.tip:simple_live_data:1.0.1-SNAPSHOT'

10, animation optimization

Trying to say here is mainly optimized using hardware acceleration to do, but to pay attention, after the animation is done, turn off hardware acceleration, turn on hardware acceleration as itself a kind of consumption. Here are a picture, second picture contrast is said to open the first one and when hardware acceleration do not open the animation effect of contrast, you can see the open render faster than a lot of open hardware acceleration on certain everything is all right it? Third picture actually shows that if you continue to fail in this view, then, there will be a performance problem, the third figure we can see the blue part of the plot of a certain improvement, indicating that, displaylist constantly failure to create and reproduce, if you want to know more details, you can view here

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

// Set the layer type to hardwaremyView.setLayerType(View.LAYER_TYPE_HARDWARE, null);// Setup the animationObjectAnimator animator = ObjectAnimator.ofFloat(myView,View.TRANSLATION_X, 150);// Add a listener that does cleanupanimator.addListener(new AnimatorListenerAdapter() {undefined @Override public void onAnimationEnd(Animator animation) { myView.setLayerType(View.LAYER_TYPE_NONE, null); } });

11 power optimization

Here is just recommendations;

a, in a case where the positioning accuracy is not using the mobile network or wifi positioning, not necessary to turn on GPS positioning.

b, verify network availability, in a network request, for example, when the user is in the 2G state, at a time when the operation is to look at a large map, downloaded probably even greater than 200 K, we do not need to send this request, so that users have been waiting for the right chrysanthemum.

Four next few content is more relaxed, are recommendations for some code

Daniel took 11 methods best summed up the year, make your app experience more silky suggestion collection

Not here to go into detail, saying only pick marked section below.

pb-> model optimization will not repeat here, there is talk about how to optimize the front.

  • Then recommend the use of SparseArray instead of HashMap, here is the Google recommended, because SparseArray province more than HashMap memory, better performance under certain conditions, mainly because it avoids the automatic packing of key such as (int into Integer type) it is an internal data storage performed by two arrays, a storage key, a further memory value, in order to optimize performance, it is also taken inside the data compression method to represent sparse array of data to save memory space.
  • Less than a last resort, do not use wrap_content ,, recommended match_parent, or fixed size, with gravity = "center", ha ha, you should understand the.
  • So why say it would be better.
  • Because the measurement process, match_parent fixed width and a height corresponding EXACTLY, while the corresponding wrap_content AT_MOST, both time-consuming comparison AT_MOST.

Five summary


This is more about performance problems I encountered in the work and summarizes some of the processing, performance optimization design every aspect of it is too much, this is impossible to summarize all of the performance problems all clearly, perhaps more than how much less are some flaws exist, the wrong place welcome that supplement.

The article is not easy, if you liked this article, or to help you take a lot of point oh praise forwarding concern. Articles will be continuously updated. Absolutely dry! ! !

Guess you like

Origin blog.51cto.com/14775360/2483496