In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to start Performance in Chrome DevTools. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Today, I would like to introduce a little brother of the Chrome dev tools family. It was called "Timeline" before Chrome 57, but now it has a longer vest-"Performance". After all, the name "long" will attract more attention.
Maybe you inadvertently started this tool and saw the colorful charts inside and felt as dizzy as I did. But after introducing it today, I'm sure you'll be as familiar with it as you are with the Swiss Army knife.
The panel is called "Performance", but the name does not specify what performance it is. Since it is a debugging tool for Chrome, it should have something to do with the page, so let's start with the performance of the page.
What will affect your page performance?
In recent years, WEB developers have made a series of plans to shorten the waiting time of users. For example, use PWA to cache more available offline resources to make web applications open faster; reduce the size of resources with the help of WebAssembly specifications to improve execution efficiency. These schemes focus on the network link, front-end resource processing speed and other dimensions, and strive to improve the user experience.
As a WEB developer, I feel that several dimensions that are deeply related to page performance are: network links, server resources, rendering efficiency of front-end resources, and user-side hardware.
Network link
Network links are often the summary of page performance, domain name resolution, switches, routers, network service providers, content distribution networks, servers, nodes on the link have problems or slow response will have a bad experience.
Server resources
In the environment of HTTP, all requests will eventually be processed by the server, and the improper handling of the server father or the slow response will directly affect the interaction between the page and the user.
Front-end resource rendering
The browser obtains the required HTML, CSS, scripts, pictures and other static resources, and draws the process that the first screen is presented to the user; or after the user interacts with the page, the browser recalculates the content that needs to be presented, and then redraws. The processing efficiency of these processes is also an important factor affecting performance.
User hardware
Initiating network request, parsing network response, page rendering and other processes all need to consume computer hardware resources. So computer resources, especially when there is a shortage of CPU and GPU resources (such as video card killer games), will also affect page performance.
Of course, the above dimensions are not ruled by lines, they are more of a staggered relationship. For example, the browser responds slowly during rendering, which may be due to poor script writing and performance bottleneck, or because graphics card killer games take up too much computer resources; for example, when analyzing front-end resource rendering, it is often necessary to analyze the acquisition time of resources combined with the network waterfall map, because the rendering page is also a dynamic process, some key resources need to wait, and some can be loaded at the same time of rendering.
Why did you sacrifice Performance?
Chrome developer tools have their own focus, such as the waterfall diagram of the Network tool has detailed information about the order of resource pull, and its focus is on analyzing network links. The Performance tool focuses on the front-end rendering process, which includes frame rate bar chart, CPU utilization area chart, resource waterfall chart, main thread flame chart, event overview and other modules, which are closely related to rendering, and you can clearly observe the entire rendering phase by using them. However, you don't have to worry about the module names mentioned above, because I'll introduce them one by one in the following space.
Start Performance with the correct posture
Open Performance
First of all, we open the Chrome anonymous window, in the anonymous environment, the browser will not have additional plug-ins, user features, cache and other factors that affect the repeatability of the experiment. Then start the developer tool. If your window is wide enough, you can see Performance in column 5 of the top tab bar. If you don't have enough width, you can click the > > button on the top right to open more tabs to find it.
What we see at this point is the default boot page for Performance. The action corresponding to the first prompt is to start recording all events on the current page immediately, and click the stop button to stop recording. The corresponding action in the second sentence is to reload the page and record the event, and the tool will automatically stop recording when the page is loaded and in an interactive state, and both will eventually generate a report (it takes a lot of computation and takes some time to generate the report).
Now the tool is ready to analyze the page.
Simple page analysis
First of all, we analyze the process of a simple page from a blank page to the finished rendering. All the sample pages of this article are placed in the following repository, cloned by command and switched to the repository root directory:
Git clone git@github.com:pobusama/chrome-preformance-use-demo.git & & cd chrome-preformance-use-demo
Then install the dependency package: npm I
Finally, launch the sample page: npm run demo1
Because it is difficult to grasp the timing of the page to start rendering, we collect rendering data through the second reload method, recording the process of beforeunload-> unload-> Send Request (the first resource request)-> load.
After the tool automatically stopped recording, we got the following report:
The four areas delineated in the figure are:
1: control panel, which is used to control the characteristics of the tool. "Network" and "CPU": limit network and computing resources respectively, simulate different terminal environments, and make it easier to observe performance bottlenecks. Turning on the "Disable JavaScript samples" option causes the tool to ignore the call stack that records the JS, which we'll talk about later. Opening "Enable advanced paint instrumentation" will record the details of some rendering events in detail, which we will talk about when we learn about these events.
2: an overview panel with 3 charts describing frame rate (FPS), CPU utilization and network resources. The frame rate is an indicator of how many images are rendered per second, and the higher the frame rate, the smoother the look and feel. The network situation is presented in the form of a waterfall diagram, in which the loading time and sequence of resources can be observed. The CPU utilization area chart is actually a continuous stacked bar chart (the enlarged version of the CPU area chart below is a schematic diagram, and the data are not strictly corresponding):
The vertical axis is CPU usage, the horizontal axis is time, and different colors represent different types of events, where:
Blue: load (Loading) event
Yellow: script Operation (Scripting) event
Purple: rendering (Rendering) event
Green: paint (Painting) event
Gray: other (Other)
Idle: browser idle
For example, the first column of the diagram: the total CPU usage is 18, and the load event (blue) and the script operation event (yellow) account for half (9). With the increase of time, the CPU utilization of script operation events gradually increases, while the usage of load events decreases to 0 around 600ms; on the other hand, the use of rendering events (purple) increases first and then decreases to 0 around 1100ms. The whole chart can clearly show the percentage of CPU usage in which time period and what events account for.
3: thread panel, used to observe the details of events, in the overview panel to narrow the scope of view, you can see the details of the line chart. The main line flame diagram is the main chart used to analyze rendering performance. Unlike the "normal" flame diagram, the flame diagram shown here is inverted, that is, the top layer is the parent function or application, the lower the call stack, the shallower the call stack, and the bottom grid (if the time dimension is not long enough, it looks like a small vertical bar) represents the top level of the function call stack.
By default, the flame graph records each layer of functions in the executed JS program call stack (down to the granularity of a single function), in great detail. When "Disable JS Samples" is turned on, the flame graph is only accurate to the event level (calling a function in a JS file is an event), ignoring all JS function call stacks under that event.
In addition, the frame thread sequence diagram (Frames) and the network waterfall diagram (Network) can view the page and resource load from the time dimension, respectively.
4: details panel. I have mentioned the incident many times before, and I think if I don't explain it, I may be sent a blade. In the Performance tool, the finest granularity of all records is events. The event here does not refer to an event in JS, but an abstract concept. If we open the main thread fire diagram and click on a box at random, we can see the details of the event in the details panel, including event name, event time consumption, initiator and other information. To give a few examples: Parse HTML is a Loading event (blue) that indicates that Chrome is performing its HTML parsing algorithm during the event time; Event is a Scripting event (yellow) that indicates that a JS event (such as click) is in progress; and Paint is a drawing event (green) that indicates that Chrome draws the composite layer.
Here are some common events, it's good to have an impression, because we have to deal with them every time we do performance analysis, it's hard not to remember them.
Another very important part of the details panel is the event time pie chart, which lists the percentage and time spent of different types of events (loading, scripting, rendering, drawing, other events, daze:) within the time period you choose. The analysis of time-consuming ratio is similar to the analysis of CPU area map-which kind of event consumes a lot of computing power and time, resulting in performance bottlenecks.
At this point, we have scanned the main features of the Performance tool, which are not comprehensive, but enough to start the journey of performance analysis. Next, let's analyze a slightly more complex animation page to really understand how to use these chart data to locate performance issues.
Nag about the browser rendering process
Knowing the rendering process of the browser is very important for our understanding and analysis. Here is a brief introduction to the rendering process of the browser:
When rendering the first screen, the browser parses the HTML and CSS files to generate the document object model (DOM) and the stylesheet object model (CSSOM); merges DOM and CSSOM to form a render tree (Render Tree); calculates the style (Style); calculates the exact position and size of each node on the screen (Layout); draws the rendering tree on the layer (Paint) according to the position calculated in the previous step The rendering engine synthesizes all the layers and finally makes them visible to the human eye (Composite Layers).
If you change the page layout, you first update the DOM through JS and then go through the process of calculating the style to compositing the image. If it is only a non-geometric change (color, visibility, transform), you can skip the layout step.
Animation analysis
With the above preparations, I believe you have begun to rub your hands. Let's run another Demo:cd chrome-preformance-use-demo & & npm run demo2 under the sample warehouse.
In the initial state, 10 small squares will move up and down at a uniform speed, and return to the original path after touching the browser boundary. "Add 10" adds 10 such squares, "Substract 10" reduces 10 squares, "Stop/Start" pauses / turns on the motion of all squares, and "Optimize/Unoptimize" optimizes / unoptimizes the animation.
How do browsers draw an animation
By default, we click on the circle in the upper left corner to record the event, and a few seconds later we can click Stop in Performance to generate analysis data. In the overview panel, we can see that after the first few hundred milliseconds, the proportion of various events in the CPU area chart changes according to a fixed period. We click on a small section of the observation, and we can see a segment of similar event groups in the main line chart. After observing several sets of events, we found that these event groups are all composed of 10 Recalculate Style + Layout loops-> Update Layer Tree-> Paint-> Composite Layers. We know that after the Composite Layers event, it means that the new page layer is visible to the human eye, that is, after such a set of events, a frame is drawn in front of the eyes.
We click "Framse" in the upper column of the main line fire diagram and find that the dotted line shortly after the Composite Layers event is the node of the next frame. This side confirms the above conclusion.
When a bottleneck appears
There is nothing wrong with the current animation. If we click the "Add 10" button 20 times and increase the number of blocks, we can see that there is an obvious stutter in the animation. If you don't feel stuttered, it means that your computer performance has beaten 99% of the users in the country (or, uh. You may have to go to the hospital to see your eyes), at this point you can reduce the CPU calculation power in the control panel. All right, let's record the performance data again:
We see a number of eye-catching reds in the report, including the big red bar on the frame rate chart and the small corner marks in the main line chart.
Once again, according to the previous idea, looking at the details of the main thread, we find that both Recalculate Style and Layout events that occur under the app.update function have warnings, indicating that the cause of the performance bottleneck may be forced rearrangement. Go to the js file to see the detailed code. In the left column, you can see that the time-consuming lines of code are dark yellow, so the code is likely to be the crux of the problem.
Note: to automatically calculate the operation time of lines of code, you need to uncheck the "Disable JavaScript Samples" option in the control panel.
So what's wrong with this line of code, and what's the rearrangement?
On rearrangement and redrawing
In short, rearranging (reflow) and redrawing (repaint) are steps to change the style of the page. The rearrangement step includes render type events such as Recalculate Style, Layout, Update Layer Tree, and the redrawing step includes paint type events such as Paint and Composite Layers. Rearrangement will inevitably result in redrawing, and the operation that causes redrawing will not necessarily result in rearrangement. Some common actions that cause rearrangement or redrawing are listed below. For more operations, see csstriggers.
Because it takes a lot of time to calculate the layout, the cost of rearrangement is much more than that of redrawing, so we need to avoid rearrangement as much as possible to achieve the same effect. For example, if both display: none and visibility: hidden meet the requirements, the latter is better.
Solve the bottleneck
Looking back at our animation Demo, in the details panel of performance, the pie chart shows the majority of rendering (rearrangement) in the animation drawing process. Combined with the code, we find out the reason: many times in the loop, immediately after updating the style location to the DOM, the DOM location is obtained through offsetTop. Such an operation forces rearrangement because the browser does not know if the DOM has changed in the previous loop and must immediately relayout to calculate the DOM location. Don't worry, you may have noticed that we also have a "Optimize" button.
To solve this problem, our optimization solution is to replace offsetTop with style.top. Although the latter takes the element position of the previous frame, it does not affect the calculation of the position of the next frame, eliminating the process of rearranging the position and reducing unnecessary rearrangement.
Note: in this example, another optimization is done in the case of non-Optimize, which is to use the requestAnimationFrame function to accumulate all style changes in one frame loop (m.style.top = pos + 'px';) in the next drawing. This not only optimizes the style of write operations, but also gives us a clearer view of the problem of offsetTop read operations.
Let's compare the reports before and after optimization:
First of all, from the pie chart and CPU area chart, the proportion of Rendering events decreased, while the proportion of Painting events increased. From the frame rate map and frames thread map, we can see that the frame rate has increased significantly, and the drawing time of an image has decreased significantly, which means that the fluency of animation has been greatly improved and the purpose of optimization has been achieved. Looking at the details, we find that in the event group that draws an animation, there are no Recalculate style and Layout events in the app.update function, so the execution time of the whole function decreases significantly, which proves that our optimization scheme works.
In this discussion of performance tools, we start with the factors that affect page performance, which leads to the dimension that Performance tools are good at-- front-end resource rendering. Then, we learned about the four main panels of the Performance tool: control, preview, threads, details, and several practical charts: frame rate bar chart, CPU area chart, main thread flame chart, frame thread sequence chart, event time consuming pie chart. Then use them to locate a performance problem and begin to solve it.
This is how to start Performance in the Chrome DevTools shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.