1. Performance optimization

1.1 Rendering Optimization

Drawing principle: The application layer transfers the surface cache data after measurement, layout and drawing to SurfaceFlinger, the system service layer, through inter-process communication. SurfaceFlinger renders the data to the screen through the display refresh mechanism.Copy the code

1.1.1 the application layer

1). OnMeasure (): use the depth-first principle to recursively obtain the width and height of all views; After obtaining the correct width of the current View childWidthMeasureSpec and childHeightMeasureSpec, you can call its member function Measure to set its size. If the child View is a ViewGroup, then it will repeat the operation until the size of its descendant View is measured. 2).onLayout(): use the depth-first principle to recursively obtain the position of all views; Once a subview is positioned in the upper left corner of the application window, combined with the width and height it determined during previous measurements, it is completely laid out in the application window. 3).ondraw ():Android supports two drawing methods: software drawing (CPU) and hardware drawing (GPU, requirements >= Android3.0). Hardware acceleration is much more efficient in UI display and rendering than CPU rendering; However, hardware also has obvious disadvantages: power consumption: GPU power consumption is higher than CPU; Compatibility issues: Some interfaces and functions do not support hardware acceleration; Large memory: the OpenGL interface requires at least 8MB memory.Copy the code

1.1.2 system layer

The main work of SurfaceFlinger is as follows: 1). In response to client events, create Layer to establish a connection with the client Surface. 2). Receive client data and properties, and modify Layer properties, such as size, color, transparency, etc. 3). Refresh the created Layer content to the screen. 4). Maintain the Layer sequence and make a clipping calculation for the final output of the LayerCopy the code

1.1.3 Inter-process Communication

Communication mode: Anonymous shared memory ShareClient; A SharedClient is created between each application and SurfaceFlinger. Each SharedClient can create up to 31 ShareDBufferStacks. Each Surface has a SharedBufferStack. So it's a window. This means that an Android application can contain up to 31 Windows, with two (<4.1) or three (>=4.1) buffers in each SharedBufferStack. Summary: The application layer draws to the buffer, SurfaceFlinger renders the cached data to the screen, and the two processes use anonymous shared memory SharedClient to cache the data that needs to be displayed.Copy the code

1.1.4 Display refresh mechanism

The Android system sends VSYNC signals every 16ms to trigger UI rendering. If each rendering is successful, it achieves the 60FPS required for smooth graphics. Android4.1 has reconfigured the display system with the introduction of three core elements: VSYNC, Tripple Buffer and Choreographer: 1).VSYNC(Vertical Synchronization) : a timed interrupt. Once the VSYNC signal is received, the CPU starts processing each frame data. 2).Tripple Buffer is a Buffer that displays data; 3).Choreographer acts as a scheduler to unify the drawing work to a point in time in VSYNC for the application to proceed in an orderly fashion; 4). FPS:Frames Per Second: the number of pictures transmitted in 1s, that is, how many times the graphics processor can brush them Per Second; 5).16ms: when human is watching the picture, the picture will not feel stuck at 60fps, but will feel stuck below 60fps; To keep the screen at 60 FPS, you need to refresh the screen 60 times in 1s, or once in 16ms.Copy the code

1.1.5 Caton root cause

1). Layout is complex, rendering cannot be completed within 16ms, resulting in frame loss; 2) overdrawing of.view results in some pixels being drawn multiple times in the same frame; 3). Too many animations are executed at the same time, resulting in heavy CPU or GPU load; 4). The UI thread processes time-consuming operations; 5).GC collection and frequent GC produce a lot of pause time;Copy the code

1.1.6 Locating analysis Tools

Orange: processing time, column height, shows that the GPU is busy; Red: execution time, the 2D rendering Display list time, red high, may be resubmitted the view caused; Blue: Measure drawing time, it takes a long time to create and update the DisplayList, blue height, it may need to be redrawn, or View's ondraw method handles too many things; Hierarchy Viewer is used to check the time of layout nesting and drawing. Layout Time button: The selected View gives the time of Measure, layout and Draw. Green: faster than other 50% views at the same stage; Yellow: slower than other 50% views at the same stage; Red: slower than other views at the same stage; If you want to see how long the View takes, click on the View. 3.Systrace Used for performance data sampling and analysis 1. Tracing system I/O operations 2. Kernel work queue 3.CPU load 4. Operation of various subsystems, etc. 5. For UI display performance, such as not smooth animation playback, rendering lag, etc., the analysis data Alert area is provided: the points with performance problems are marked and detailed description is provided. For example, the View takes a lot of time in Measure Layout, resulting in the occurrence of JanK (the same frame is drawn many times). The suggestions are as follows: Avoid controlling layout during animation playback. CPU area: shows the running thread and process, start time, and duration information; Application area: The Frames analysis is given. Each frame is a circle, three colors; Green: render smoothly yellow and red indicate render time over 16ms, red is more severe; 4. Traceview is used to collect data and analyze trace file 1. 2. Perform the following operations for multiple times: 1. Perform operation 2 in AS Tool. Debug. StartMethodTracing stop --> Generates a trace file; 3. Analysis: such as Incl Real time to check the Real time;Copy the code

1.1.7 Optimization Strategy

1. Reasonable use LinerLayout, RelativeLayout, FrameLayout ConstraintLayout layout container 2, etc. Use <include> tags to reuse layouts 3.. Use the <merge> tag to remove redundant levels 4. Use the ViewStub to speed up loading 5. Avoid GPU overdrawing 1. In AN XML layout, controls overlap and all have set backgrounds 2.View's onDraw() method draws multiple times in the same area 1. 2. In the custom View's onDraw() method, use canvas.cliprect () to specify the drawing area to prevent overdrawing of overlapping components 3. Enable optimized UI layout: The application usually has a splash screen. Optimize the UI layout of the splash screen. You can detect frame loss by using Profile GPU Rendering. Start loading data logic optimization: partial loading, asynchronous loading and delayed loading strategies can be adopted to improve the startup speed of the application. Data preparation: data initialization analysis, and thread initialization can be considered when loading data. Reasonable refresh mechanism to minimize the number of refresh and avoid high CPU threads running in the background to narrow the refresh areaCopy the code