Summary of Android performance patterns on YouTube (part)

Source: Internet
Author: User
Tags webp wrappers skia

1. Familiarize yourself with the use of the Logcat,memory,cpu,gpu,network Analysis window in Android Studio. Once you've configured a sudden drop in memory, it should be the GC that works. These garbage collection activities usually do not affect performance too much, but they occur frequently over a short period of time, which can quickly consume frame time or cause performance problems.

2. Memory leaks: Refers to objects that are no longer used by the application, but garbage collection does not recognize them. As a result, they remain in your memory.
Memory heap in the Android runtime environment:

The Android runtime memory heap is effectively partitioned into different chunks, depending on the type of configuration, as well as the optimal collation of these configurations based on the system for future garbage collection activities. When new objects are configured, these characteristics are taken into account to determine which chunk is most appropriate for this configuration.

The two main principles of 3.GC:
1. Find data objects that will not be used in the program.
2. Reclaim the resources that these objects occupy.
Know two points:
1. The longer the garbage collection time is applied within the specified time, the less logical processing time remaining to complete rasterization within 16MS. If there is a continuous mass of garbage collection, or long garbage collection, may be more than 16ms, it will lead to user visual lag.
2. Be aware that your code stream may perform some work, forcing the GC to occur more frequently, or for longer periods of time, for example, when you are configuring a large number of important objects into an internal loop, it can take a long time. This large heap of objects will contaminate the memory heap.

4. Memory Loss: Memory loss occurs when you configure a large number of objects in a short time and release them in a very short time. If memory jitter is seen in memory monitoring, then sorta from there.
Workaround:
1. To ensure that there is no inside loop, configure the object for obvious reasons. Try to move them out of the loop, or avoid them directly. There is also the same in OnDraw function (essentially the same).
2. If you do not want to create an object, you can consider Object pool mode . In fact, you'll have a pool of objects for configuring a set of objects, and your code doesn't have to go into the heap every time, and it can fetch the available objects from the memory pool.

The disadvantage of this model is that you have to dispose of the objects yourself and release them into the memory pool when you are done with them. This means that for high-disturbance objects, you will need to expend some effort to manage these objects reasonably when created and destroyed. (Much like the pattern in the GetView method).

5. Introduction to the Jobscheduler API: How to do things under low battery conditions. Tool Battery Historian.

The word is to leave the non-urgent work to be done when the conditions are fuller.

Better conditions include WiFi, charging, phone in hibernation etc...

If your app has tasks that meet the following conditions, you can try using the Jobscheduler mechanism to perform tasks:
Non-user-oriented tasks that can be deferred (such as periodic database data updates)
Work that you want to perform when charging (such as backing up data)
Tasks that require access to a network or Wi-Fi connection (such as pulling built-in data to the server)
Many tasks that you want to run regularly as a batch

The work you need to do on the code is to put the related tasks into Jobservice and set the service launch conditions according to the application, which can be the following:

Start when the device is charging
Boot when the device is connected to an unlimited traffic network (WIFI)
Start when device is idle
Complete before a specific deadline or with minimal delay
Only when the condition is met will the system start the scheduled task.

As long as everything is in place, the increase in mobile phone life is certainly obvious.

6. About Overdraw:
Excessive drawing occurs because the hardware uses too many cycles to draw pixels on the screen, which in the end do not form a picture.
Now the Android system will automatically minimize over-rendering, and it can try to avoid drawing items that are completely hidden beneath opaque surfaces.
But this technology has not developed in depth, there is no complex custom view, and can not cover the OnDraw method. In these cases, the system is unable to understand how you draw the content, making it difficult to know what you should avoid.
Workaround: Help the system to observe this process by using the Canvas.cliprect API. This feature allows you to specify a drawing boundary for your own view, and only items within the rectangle can be drawn.
This API also protects the CPU and GPU performance:
CPU: Each canvas draws a command and submits them to OpenGL ES for drawing with a little extra burden. Any drawing commands other than Cliprect are not submitted to the hardware, and there is no additional burden.
Now, any content that is partially intersected with the cliprect will still be drawn.
This is also why Cliprect can help define the exclusion rectangle on the GPU side, allowing the GPU to avoid shading the cropped part from the pixel level.

In addition to Cliprect, you can also use the Qucikreject API, which allows you to test the cross-section of Cliprect within your OnDraw function.

You can use the GPU Overdraw tool for monitoring.

7. How the Drawing works:
How Android works, when updating visualizations, remember that before the Android draws a pattern on your device, it transforms the advanced XML file into a file that the GPU can accept and then renders the screen.
This has to do with an internal object, called the display list . The display list basically contains all the required information for GPU rendering.
Minimizing the layout failure is a good start to improve the overall performance of the rendering system.

Monitoring tools:
1.Profile GPU Rendering

2. Always use the hierarchy Viewer to check your view level and try to keep it flat.

8. Draw:

buttons, or paths, etc. that need to be drawn to the screen, they first need to be converted to pixels and textures within the CPU before they can be sent to the GPU for rasterization.
Optimizing rasterization means storing as much data as possible, and getting it as fast as possible, and then staying there for as long as you can without moving him.
For commonly used drawing patterns, textures, Android is optimized and does not need to be converted by the CPU, but is directly present in the GPU, thus reducing the time of intermediate conversions.

9.Profile GPU Rendering:

Blue, red, orange directly reflect the ratio of the Android render channel.
Blue: Represents the drawing time. Or, how long does it take to generate and update your display list in Java. Remember that before the view is rendered, it must be converted into a format that is suitable for the GPU. Simply put, this may be just a few drawing commands, and when complicated, we may need to embed a custom path into the canvas object. Once completed, the results are displayed by the system as a display list. Blue Records the time it takes to complete these two steps for all the views that need to be updated. :

If the blue is elevated, it may be:
1. A bunch of views suddenly failed.
2. Some of the custom views include some complex logic in the OnDraw feature.

Red: Represents the execution time. This is the time consumed by Android 2D rendering when the display list is executed. The more complex the view, the more complex commands are required for OpenGL to draw.
If the red is elevated: it may be:
1. A complex view.
It is important to note the dense column peaks, as well as the possibility of repeatedly uploading a large number of views for redrawing. These views are not necessarily invalid.

Orange: Represents the processing time. This is the CPU that tells the GPU that it finishes a frame rendering. This activity is a blocking call. Therefore, the CPU waits for information from the GPU to perceive the instructions it receives. If Orange is high, it means that the GPU is handling a lot of work, resulting in a lot of complex views that require a lot of OpenGL rendering commands to handle.

10.VSYNC.
Refresh rate: The number of times the display is updated in the screen per second.
Frame rate: The number of frames per second that the GPU can draw. For example, 60fps. In this case, the higher the frame rate, the better.
Solve two different frequency problems: Double buffering Technology , also known as background buffering .
In fact, when the GPU draws a frame into memory, it copies it to the memory sub-area, also called the frame buffer, when it draws the second frame, it completes the background buffer, the frame buffer is unaffected, and now, when the screen refreshes, it will be refreshed from the frame buffer that is not in the drawing process.

This is going to use the VSync, also known as vertical synchronization .
Frame rate always ensures that your GPU can quickly get the data it wants and that it has time to draw before the next screen refreshes. Android will refresh the screen every 16ms, if the frame rate is less than 60, then when the screen is refreshed, the rendering will be detected not ready, then it will not be refreshed (that is, save the original appearance). In this way, we will see an image of the same frame (possibly longer) within 32ms.

11. Go to developer mode and use the tool: "Show GPU repeat drawing" for monitoring. Ability to detect overdraw.

12.monkeyrunner,espresso.

13. Memory jitter caused by loading images:
1. Using object pooling
2. You can instruct the decoder to use a saved memory slice to load the bitmap instead of creating a new bitmap. Use the Inbitmap property in the object Bitmapoptions (bitmap feature) to resolve. When you assign the Inbitmap property to an existing bitmap, any decoding and loading instructions for the next pixel data will reuse that existing bitmap instead of configuring a new object from the heap.

Note the point:
1. For the following SDK 18, the loaded bitmap and the reused bitmap must be of the same size to work properly. For more than 19, the loaded bitmap is larger or equal than the original.

2. Although it can be reused across pixel formats, this is a multi-section process, and a simple method is to use a separate bitmap for each of your pixel formats. This is a good trouble!
3. Use the glide library, or another open source framework.

14.pre-scaling Bitmaps:
For a bitmap that produces a power size that is not the original 2. First, use Insamplesize to convert it to the 2 power below the target. Then use indensity and intargetdensity to scale the build specifications to the exact size you want. The combination of these two methods is very fast, because insamplesize reduces the number of pixels, and the steps based on the output density need to apply size reset filtering to those pixels.

Practical class Library: Glide,picasso. The ability to handle this kind of bitmap size reset code, there are other features, such as asynchronous decoding and caching.

15.PNG files are a major part of the Android image content, especially if you have a lot of UI elements in your app, rather than picture data. PNG they are easy to swell and swell at a high frequency.
Optimization method:
1.

2. Use the WEBP format. It supports alpha transparent processing, lossless and lossy compression, and animations. In fact, WEBP and lossy processing steps will only help you deal with the size in the image release phase. Once the images have been loaded into memory, they have been extracted to the normal format, so they can be used for rendering. This means that all file compression will only help you with data transfer, not CPU memory usage. Once the file leaves the disk into memory, some good compression saves are gone.

16. Smaller pixel format:

The so-called performance, is the choice. Image memory size, visual effects, load time. This is all you need to balance so your application can achieve the best performance. The Dalvik version of the Android garbage collector is non-compressible, meaning that when the object is freed, other objects are not tuned for optimization to free up space. This represents a big problem with bitmaps, which is probably the largest contiguous chunk of memory that you will actually configure within your app. The less contiguous free space in your heap memory means that the configuration of the bitmap may fail, causing garbage collection events to be triggered to free up space in other locations, so the configuration may eventually succeed or an out-of-memory error may occur.

The reason these pictures are so large in memory is that before you can use these JPEG or PNG files, they are loaded into memory and decoded into a format that the system can render, meaning that once they are loaded, they are no longer their compressed format. And, by default, when a picture is loaded as a bitmap in Android, the format defaults to agbb_8888, and the other formats are rgb_565,argb_4444,alpha_8 by setting.

17. It is important to improve performance and reduce workload. But sometimes working hours and workloads are just as important. Several important APIs:
1.AlarmManager

Set up an off-time alert. Do not set the on-time alert when not necessary.
2.SyncAdapter (Sync adapter): It provides batch processing in exactly the same way as a non-accurate alert. But they will also bring you a network connection check and automatic retry.

If your goal is API21 above, directly use the more powerful 3.
3.JobScheduler

18. Custom View:
Error:
1. Waste time charting things that haven't changed.
2. Wasting time and bandwidth draw pixels that never show up. Because they were obscured by other objects.
3. Waste too much time running the code that draws the function.

For 1:
Remember, all drawing starts with calling the View.invalidate code.
Principle one: If there is no change in the view, you do not have to redraw it.

Principle two: Always pass a rectangle to void. A dirty Rectangle (dirty rect), giving the system hints that the part of the view has been changed. The shading system uses this rectangle to help determine when to invoke the drawing function.
When your view is animated, OnDraw is called 60 times per second. Unlike most other code, the drawing code must run in the UI main thread.

19.ANR:
Often we suspect a system call that will block indefinitely, such as a disk or network access. Normally, it can be done quickly, but once hardware + software + bad luck is combined, they will explode.
Monitoring tool: Strict mode in developer model.
Strict mode:
Thread policy: Threading rules have the ability to detect slower blocking methods.
VM Policy: Detects options for various memory drains.
Two rules complement one another.
If you have low memory, a normal configuration can block hundreds of milliseconds. It is likely that there is at least one blocking call on your application's main thread that is waiting to cause glitches, dropped frames, and even ANR. Strict mode will help you find them.

20. Avoid configuration in OnDraw (allocation):
Typical configuration in a drawing function, such as painting, path, typeface, etc. But these classes all have something in common, and they are all wrappers for local objects. The 2D drawing system of the Android system relies on a library of graphics processing functions called Skia. Skia is written in C + +. Many of the classes in Android.graphics are actually wrappers for local C + + objects. and C + + objects have destructors that you explicitly call destructors before you reclaim the memory of an object. This means that you want to run finalizers (finalizers), which is very bad for performance. and destructors must, along with other things, synchronize on the local heap lock. So there is always the possibility that they will block the main thread of the UI for a long time to drop frames. In other words, the constant creation and discarding of an image object essentially tells the system that it wants the application to be interrupted by an indefinite length of time within an unpredictable interval.

Workaround: In essence, do not new too many objects in the OnDraw function. Use the refactoring tools inside Android Studio. Use the Extract field (Fetch field) to move these objects out of the drawing function and into the body of the class that can be reused, and leave the fields static if possible. This way, you can re-use objects in multiple instances of your class. This is a good way to do this, especially if your view is used in list items . Because in this case it will be created multiple times.

21.hidden Cost of transparency:
Alpha Transparent combination is a cool effect that helps the app sell well.
When you render opaque elements, each pixel needs to be written only once, but when you blend, each pixel is drawn at least 2 times. Because we need to know what's inside the alpha transparent blend view to blend in. In some cases, a single alpha transparent blend view will cause a full branch within your view level to be drawn 2 times. Potential performance problems, because the hardware layer has many front-end costs, but it becomes cheap over time. When you use the hardware layer for the first time, it is much more expensive than drawing directly to the screen.
The saved part is in the back, when you reuse the layer without replacing the content. However, the Android system defaults to each frame, and the renderer discards the hardware layer. Therefore, to achieve optimization, it is necessary to explicitly remind the system, re-use the hardware layer.
Optimization:
1. Re-use the hardware layer. Android 16 above directly uses intermediate statements, allowing animations to automatically manage layer types. 16 Use the preceding sentence and the last sentence.

2. Clear function, according to business rewrite view.hasoverlappingrendering.

22. Use the Lint tool in Android Studio to check for static code optimization issues. There may be more things to check, so there are a few simple suggestions:
1. Make sure you set the memory configuration in the drawing code (allocations within drawing code) and throw an error.
2. Include overdraw detection in the warning class.

23.LRU Cache:
Set the cache size based on the total amount of memory available to your app:

Getmemoryclass points out that in order for the system to work best, your app should set the memory limit itself.

24. About iterators: In Java, for stability and maintainability, iterators are required to iterate over arrays or other data structures. But this also has the performance loss. It should be considered carefully in the case of very heavy performance.
Test: Three grammar tests for ArrayList and vectors (for, standard iterator, simplified iterator (for Item item:list)). The results are as follows:

Note: Before replacing, see if the performance can be significantly improved, which is the use of stability and maintainability in exchange for performance of the example.

25. With regard to object pool, there are many controversies on the Internet, and its implementation method is also more difficult. Be sure to find out if it's worth it in a specific application.
Reference:
Https://www.youtube.com/watch?v=bSOREVMEFnM&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE&index=42
There are also articles in pocket.

26.network:

Current diagram:

Request: 1. Do it now (e.g. user active pull-down refresh) 2. Do it sometime in the future (with Jobscheduler)
For now Optimization:
1. Take advantage of the pre-load function (prefetch). Essentially, try to predict what the user might need in the next 5-10 minutes, or 1-5m data, to get that content in advance. This will get rid of the future burden of small, independent requests.
2. Be sure to compress any content that you can control to upload or download. Overall, the battery performance of CPU cycles that require compression or decompression of content is typically significantly lower than the cost of the radio used to deliver that load to the network.
Monitoring tool: Networking Profiling (Network connection profiling).

27. The performance of the network connection is to shorten the time that the user requests the data to our return data. Many things affect this variable. such as bandwidth delay, cellular connection speed.

Principle:
1. Reduce Radio Active Time
2. Reduce the size of the acquisition data

Classification of Network requests:
1. What the user asks you to do. (Manual refresh)
2. The server will update you (back to a response, with new social data available)
3. Data that needs to be uploaded frequently (upload analysis, search for any device location)

The latter two are the focus of optimization.
1. You should never poll the server regularly for updates! , which is wasting bandwidth and power, letting the server tell you nothing has changed
Workaround: For example, with Google Cloud push, you'll be prompted to apply new content to the server. Gcmnetworkmanager is a Google Play service API that can help you plan your network connection-oriented tasks and process batches for you.

28. About compressing data:
Https://www.youtube.com/watch?v=Eb7rzMxHyOk&list=PLOU2XLYxmsIJGErt5rrCqaSGTMyyqNt2H&feature=iv&src _vid=l5me3tpjejs&annotation_id=annotation_296967671

http://www.html5rocks.com/en/tutorials/speed/img-compression/

Https://www.youtube.com/watch?v=whGwm0Lky2s&feature=iv&src_vid=l5mE3Tpjejs&annotation_id= annotation_1270272007

http://www.html5rocks.com/en/tutorials/speed/txt-compression/

Thinking carefully about how often you send XML and JSON packets, you may find that you should not send these raw text data, but instead use the PROTOBUFS or flatbuffers format for leverage

Stop updating!!! See Hu classmate's summary, than I write a lot better. Abandoned Pits!!!
Delivery address: http://hukai.me/blog/archives/

Summary of Android performance patterns on YouTube (part)

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.