Android Performance Optimization Model
We can see how the rendering performance is performed using the monitorgpurendering described above, and also the showgpuviewupdates in the developer's options to see how the view is updated. Finally, we can also view the layout by Hierarchyviewer this tool, which makes the layout as flat as possible, and removes the necessary UI components, which can reduce the computational time of Measure,layout.
8) Overdraw,cliprect,quickreject
One of the most important aspects of performance problems is the excessive complexity of drawing operations. We can use tools to detect and fix overdraw problems with standard UI components, but it's a bit of a problem for highly customizable UI components.
One trick is that we can significantly improve the performance of drawing operations by executing several APIs methods. As mentioned earlier, rendering updates for non-visible UI components can cause overdraw. For example, after the navdrawer has been slid out of the previously visible activity, if you continue to draw UI components that are not visible in navdrawer, this leads to overdraw. To solve this problem, the Android system minimizes overdraw by avoiding drawing components that are completely invisible. View that is not visible in the navdrawer will not be wasted resources.
Unfortunately, for overly complex custom view (overriding the OnDraw method), the Android system cannot detect what is going on in OnDraw, and the system cannot monitor and automatically optimize, and there is no way to avoid overdraw. But we can use Canvas.cliprect () to help the system identify those areas that are visible. This method allows you to specify a rectangular area that will be drawn only within this area, and other areas will be ignored. This API can be very helpful for those custom view that has multiple sets of overlapping components to control the displayed area. While the Cliprect method can also help conserve CPU and GPU resources, drawing instructions outside of the Cliprect area will not be executed, and components that are part of the content within the rectangular region will still be drawn.
In addition to the Cliprect method, we can also use Canvas.quickreject () to determine if a rectangle is not intersected, skipping the drawing operations in the non-rectangular areas. After doing those optimizations, we can look at the effects through the Showgpuoverdraw described above.
9) Memorychurnandperformance
Although Android has a mechanism for automating memory management, improper use of memory can still cause serious performance problems. Creating too many objects in the same frame is something that needs special attention.
The Android system has a generationalheapmemory model that performs different GC operations based on the different memory data types in memory. For example, recently allocated objects are placed in the Younggeneration area, where objects are usually quickly created and destroyed quickly, while the GC operation speed of this area is also faster than GC operations in the Oldgeneration region.
In addition to the speed difference, any action on any thread will need to be paused when the GC operation is performed, and other actions will continue to run after the GC operation is complete.
In general, a single GC does not take up too much time, but a large number of non-stop GC operations can significantly occupy the frame interval (16ms). If there are too many GC operations in the frame interval, then natural other similar calculations, rendering operations such as the availability of time has become less.
There are two reasons why a GC can be performed frequently:
Memorychurn memory jitter, memory jitter is due to the large number of objects being created and being released immediately within a short period of time.
Generating a large number of objects in an instant can seriously occupy the younggeneration memory area, and when the threshold is reached, the GC will also be triggered when there is not enough space left. Even though each allocated object consumes little memory, stacking them together increases the pressure on the heap, triggering more other types of GC. This operation has the potential to affect the frame rate and make the user aware of performance issues.
There is a simple and intuitive way to solve the above problem, and if you look inside the memorymonitor to see how many times the memory has changed in a short time, this means that memory jitter is likely to occur.
We can also use Allocationtracker to see the same objects that are constantly in and out of the same stack within a short period of time. This is one of the typical signals of memory jitter.
After you have roughly positioned the problem, the next fix is relatively straightforward. For example, you need to avoid allocating objects to memory in a for loop, and you need to try to move the creation of objects outside the loop body, and the OnDraw method in the custom view needs to be noticed, and the OnDraw method is called every time the screen is drawn and the animation is executed. Avoid complex operations within the OnDraw method and avoid creating objects. For those who cannot avoid the need to create objects, we can consider the object pool model, through the object pool to solve the problem of frequent creation and destruction, but it is important to note that after the end of use, you need to manually release objects in the object pool.
) garbagecollectioninandroid
The recycling mechanism of the JVM is a great benefit to developers, and instead of dealing with the allocation and recycling of objects at all times, you can focus more on more advanced code implementations. Compared with languages such as java,c and C + +, they require developers to focus on the allocation and recycling of objects, but in a large system, it is unavoidable that some objects forget to recycle, this is the memory leak.
The GC mechanism in the original JVM has been largely optimized in Android. Android is a three-level generation memory model, the most recently allocated objects will be stored in the Younggeneration area, when the object in this area to reach a certain amount of time, it will be moved to Oldgeneration, Finally to the Permanentgeneration area.
Each level of memory area has a fixed size, and since then constantly new objects are assigned to this area, when the total size of these objects quickly reached the threshold of this level of memory area, will trigger the GC operation, in order to make room for other new objects.
As mentioned earlier, every time a GC occurs, all of the threads are in a paused state. The time taken by GC and which generation it is also has a relationship, younggeneration each GC operation time is the shortest, oldgeneration second, permanentgeneration the longest. The length of execution is also related to the number of objects in the current generation, and traversing a lookup of 20,000 objects is much slower than traversing 50 objects.
While Google's engineers are trying to shorten the time it takes for each GC, it's important to pay particular attention to GC-led performance issues. If you accidentally perform an action to create an object inside the smallest for loop unit, this can easily cause a GC and cause performance problems. With Memorymonitor we can see the memory footprint, every instant the memory is reduced because of the GC operation, if there is a large amount of memory up and down events in a short period of time, it is likely that there is a performance problem here. We can also use the Heapandallocationtracker tool to see what objects are allocated in memory at this time.
One) Performancecostofmemoryleaks
Although Java has a mechanism for automatic recycling, this does not mean there is no memory leak in Java, and memory leaks can easily lead to serious performance problems.
Memory leaks mean that objects that are no longer used by the program cannot be recognized by the GC, which causes the object to remain in memory and consume valuable memory space. Obviously, this also makes the memory area of each level of generation less space available, and GC is more susceptible to triggering, which can cause performance problems.
Finding a memory leak and fixing the vulnerability is tricky, and you need to be familiar with the code you're executing, knowing exactly how it works in a particular environment, and then carefully troubleshooting it. For example, do you want to know if an activity in the program exits with a complete release of the memory it used before? First you need to use Heaptool to get a memory snapshot of the current state while the activity is in the foreground, and then you need to create a blank activity that takes up almost no memory to jump to the previous activity. Next, when jumping to the blank activity, call the System.GC () method to ensure that a GC operation is triggered. Finally, if the memory of the previous activity is all properly freed, there should be no object in the previous activity in the memory snapshot after the blank activity is started.
If you find that there are some suspicious objects that are not released in the memory snapshot of the blank activity, then you should use Alocationtracktool to look up the specific suspicious objects. We can start listening from the blank activity, start to observe the activity, and then go back to the blank activity end listener. After doing this, we can look closely at those objects and find out the real killer of the memory leaks.
Memoryperformance)
Typically, Android has a lot of optimizations for GC, and while performing GC operations will pause other tasks, in most cases GC operations are relatively quiet and efficient. However, if our use of memory is inappropriate, which causes the GC to execute frequently, this can cause a small performance problem.
To find memory performance issues, Androidstudio provides tools to help developers.
Memorymonitor: It is a dangerous signal to see the memory occupied by the entire app and the time the GC is taking place, a large number of GC operations in a short period of time.
Allocationtracker: Use this tool to track the allocation of memory, as mentioned earlier.
Heaptool: View the current memory snapshot to facilitate a comparative analysis of which objects may be leaking, please refer to the previous case.
Tool-memorymonitor)
The memorymonitor in Androidstudio can help us to see the memory usage of the program very well.
Batteryperformance)
Power is actually one of the most valuable resources in handheld devices, and most devices need to be recharged continuously to maintain their use. Unfortunately, for developers, power optimization is the last thing they'll think about. But you can be sure that you can't make your application a big drain on your battery.
Purdueuniversity studied the power consumption of some of the most popular applications, with an average of about 30% of the power being used by the program's core methods, such as drawing pictures, placing layouts, and so on, and the remaining 70% or so of the charge is reported data, check location information, Time to retrieve background advertising information used. How to balance the power consumption of both is very important.
There are several measures that can significantly reduce the consumption of electricity:
We should try to reduce the number of wake-up screens and duration, use Wakelock to handle wake-up problems, be able to perform wake-up operations correctly, and close the operation to sleep according to the set-up time.
Some actions that do not have to be performed immediately, such as uploading songs, picture processing, etc., can wait until the device is charging or has sufficient power.
Triggering the operation of the network request, each time will keep the wireless signal for a period of time, we can package the fragmented network requests for one operation, to avoid excessive wireless signal caused by the power consumption. For the network request caused by the wireless signal power consumption, you can also refer to here.
We can find the power consumption statistics of the corresponding app using the phone settings option. We can also use Batteryhistoriantool to view detailed power consumption.
If we find that our app has too much power consumption, we can use JOBSCHEDULERAPI to handle some tasks on a timed basis, for example, we can take the task heavy operation until the phone is charging, or when connected to WiFi.
understandingbatterydrainonandroid)
The calculation and statistics of power consumption is a troublesome and contradictory thing, recording the power consumption itself is also a charge of the matter. The only viable option is to use a third-party monitoring device so that the actual power consumption can be obtained.
When the device is in standby, the power consumption is very small, take N5 as an example, turn on airplane mode, you can standby for nearly 1 months. But to light the screen, the hardware modules need to start working, which consumes a lot of power.
After you use the Wakelock or Jobscheduler wake-up device to handle timed tasks, be sure to get the device back to its original state in time. Every time you wake up a wireless signal for data transfer, it consumes a lot of power, which is more expensive than Wi-Fi and other operations. Repairing the power consumption is another big issue, and it's not going to go ahead.
Batterydrainandwakelocks)
It is a contradictory choice to keep more power efficiently and to encourage users to use your app to eliminate electricity consumption. But we can use some better ways to balance the two.
Let's say you have a lot of social apps in your phone, and even when your phone is on standby, it's often woken up by these apps to check for new data syncing. Android will constantly turn off all kinds of hardware to extend the phone's standby time, first the screen will gradually darken until shut down, and then the CPU goes to sleep, all this is to save valuable power resources. But even in this state of sleep, most applications will still try to work, and they will constantly wake up the phone. One of the simplest ways to wake up a phone is to use the Powermanager.wakelock API to keep the CPU working and prevent the screen from darkening off. This allows the phone to be awakened, perform work, and then go back to sleep. Knowing how to get Wakelock is simple, but releasing wakelock in a timely manner is also very important, and improper use of wakelock can lead to serious errors. For example, the data return time of the network request is uncertain, which causes only 10s of things to wait for 1 hours, which will make the power wasted. This is also why it is critical to use the Wakelock.acquice () method with timeout parameters. But just setting the timeout is not enough to solve the problem, such as setting how long the timeout is appropriate? When to retry and so on?
To solve the above problem, the correct way may be to use a non-precision timer. Normally, we set a time to do something, but it might be better to change the time dynamically. For example, if you have another program that needs to wake up 5 minutes later than the time you set, it's best to wait until that time when the two task bundles work together simultaneously, which is how the non-precision timer works at its core. We can customize the scheduled tasks, but if the system detects a better time, it can postpone your task to save power consumption.
This is exactly what Jobschedulerapi is doing. It combines the ideal wake-up time based on the current situation and task, such as when you are charging or connecting to WiFi, or when the task is centralized. We can implement many free scheduling algorithms through this API.
The Batteryhistorytool has been released from Android5.0, which can be used to see how often the program wakes up, and who wakes up and how long it lasts.
Keep an eye on the program's power consumption, and the user can see the big spenders by setting options on the phone, and may decide to uninstall them. Therefore, it is necessary to minimize the power consumption of the program.
MORE: Black Hat technology http://www.heimaoxuexi.com
Android Performance Optimization Model