Your website is running properly. Now let's make it run faster. The website performance is determined by the page loading speed and code execution efficiency. Some services can make your website load faster, such as compression and CDN, but make code execution faster.
Minor changes in the Code may have a huge impact on performance. The quick and flexible website and the terrible "no response script" dialog box may have only a few lines of code. This article shows you how to use Chrome Developer Tools to find these lines of key code.
Set a baseline
Let's take a look at a simple "color sequencer" app, which shows a grid composed of various colors. You can drag and drop these colors for mixing. Each vertex is a div tag with CSS that makes it look circular.
It is tricky to generate these colors, so I used "Making Annoying Rainbows in Javascript ".
The page was loaded very quickly, but it took some time and flashed before rendering. It is time to analyze the performance of this page to make it faster.
When starting performance optimization, you must set a baseline to determine the speed of the page. This baseline allows you to know whether you have optimized the baseline and helps you weigh the pros and cons. In this article, we will use chrome Developer Tools.
The Performance Analyzer (profiler) is part of the chrome developer tool. Click the tool menu under the wrench to open it. Firebug also has some performance evaluation tools, but webkit kernel browsers (chrome and safari) are the best in terms of Code Performance Analysis and timeline display. Chrome also provides a great event tracking tool called speed tracer.
Start recording under the time line (timeline) label, load the page, and stop the record, so that a baseline is set. (Open the chrome developer tool, click the "timeline" tab, and then click the black "record" icon at the bottom of the window to start recording ). Chrome is intelligent and records are started only when the page starts loading. I recorded three times and obtained the average value, in case my computer ran slowly during the first test.
My average baseline, that is, from the first request to the end of page rendering, took 1.25 seconds. This time is not too long, but it is not good for such a small page.
I want to make code execution faster, but I don't know what slowed it down. The Performance Analyzer (profiler) helps me find the cause.
Create a Profile
The time line (timeline) tells us how long it takes to run the code, but it does not help us to know what happened when the code is running. We can make some changes and continuously test the running time of each code generation, but this is blind. Profiles provides us with better methods. Profiler tells us which functions take most of the time for execution. Let's switch to the chrome developer tool's "Profiles" tab to start performance testing. Here we provide three types of performance testing.
1. javascript cpu performance test
Displays the CPU usage of javascript.
2. css selector performance test
Displays the CPU used to process the CSS selector.
3. Stack snapshots
Displays the memory usage of javascript objects.
We want javascript code to be executed faster, so we can test the CPU performance. Let's start performance testing, refresh the page, and then stop.
Through performance analysis, we first know that many functions are being executed. The color sequencer uses jQuery and jQuery UI to handle management plug-ins and parsing expressions. I found that the top of the list is the decimalToHex and makeColorSorter functions. These two functions occupy the CPU 13.2% time, which is a good place for optimization.
Click the "Next" arrow next to a function call to view the complete function call stack. After expansion, we can see that decimalToHex is called by makeColorSorter, and makeColorSorter is called by $ (document). ready.
The Code is as follows:
$ (Document). ready (function (){
MakeColorSorter (. 05,. 05,. 05, 0, 2, 4,128,127,121 );
MakeSortable ();
});
Finding out where these two functions are called makes it clear that color sorting is not the biggest performance problem. In general, performance problems are caused by redundant sorting operations, but it takes more time to add DOM elements than sorting in my code.
I want to make these functions run faster, but first I want to separate my change zones. Many things will happen during page loading. I don't want to analyze the performance that affects me.
Segmentation
I made a second version. In this version, the "color sorter" is loaded only after I click the button, rather than when the document ready is loaded. This separates the document loading process so that I can test the color classification performance only. After performance tuning, I can immediately change it back.
Let's call the new function testColorSorter and bind it to a clickable button.
Function testColorSorter (){
MakeColorSorter (. 05,. 05,. 05, 0, 2, 4,128,127,121 );
MakeSortable ();}
<Button id = "clickMe" onclick = "testColorSorter ();"> Click me </button>
Changing the application may cause unexpected results before performing performance analysis. This change seems safe, but I still need to re-run the Performance Detector to see if I accidentally changed anything. I will start a new Performance Analysis and click the button in the application to stop.
First, I noticed that the loading of the decimalToHex function takes only 4.23% of the time. This is the place where code execution takes the most time. We create a new baseline to see how much code this solution has optimized.
Some events are triggered before I click the button, but I only pay attention to the time it takes to render the color sorter from my mouse to the browser. When the mouse clicks within 390 milliseconds, the rendering event is triggered within 726 milliseconds. 726 minus 390 get my baseline 336 milliseconds. Like the first baseline, I repeated three times to get the average value.
Now, I know how to obtain and get the exact running time of the Code, and we are ready to solve the problem.
Make code more efficient
The Performance Analyzer only tells us which function causes problems, so we need to check the function source code to understand what the function has done.
Function decimalToHex (d ){
Var hex = Number (d). toString (16 );
Hex = "00". substr (0, 2-hex. length) + hex;
Console. log ('converting '+ d + 'to' + hex );
Return hex;
}
Each color point in the color sorter has a hexadecimal color value, for example, # 86F01B and # 2345FE. these values indicate the values of the primary colors red, green, and blue. For example, the background color is # 2456FE, indicating that the red value is 36, the green value is 86, and the blue value is 254. Each value must be between 0 and 255.
The decimalToHex function converts the color represented by RGB values to the hexadecimal color we use on the page. This function is very simple, but I still leave a debugging code console. log that can be removed.
The decimalToHex function also adds a complement to the number. This is very important because some 10-digit numbers correspond to one hexadecimal number. For example, 10 in decimal format corresponds to C in hexadecimal notation, but a two-digit number is required in CSS. To make the hexadecimal conversion faster, we make this code not so generalized. I know that the length of each number to be supplemented is 1, so we can rewrite this function.
Function decimalToHex (d ){
Var hex = Number (d). toString (16 );
Return hex. length = 1? '0' + hex: hex;
}
In the third version, the color sequencer changes the string only when it needs to be supplemented, and does not need to call the substr function. With this new function, the running time is 137 milliseconds. After performing a performance test on the code, we can find that the decimalToHex function only occupies % 0.04 of the total time and reaches the lower part of the list.
We can also find that the most CPU-Consuming function is jQuery's e. extend. merge. I don't know how this function works, because the code is compressed. I can use the developed jQuery version, but I found this function was called by makeColorSorter. So the next step is to let the function be executed faster.
Reduce changes
The colorful colors in the color sequencer are generated using an over-sine curve. Set a center point in the spectrum and create the curve with a certain offset. This turns the color into a "Rainbow model ". We can also change the color by changing the frequency of the three primary colors.
Function makeColorSorter (frequency1, frequency2, frequency3, phase1, phase2, phase3, center, width, len ){
For (var I = 0; I <len; ++ I ){
Var red = Math. floor (Math. sin (frequency1 * I + phase1) * width + center );
Var green = Math. floor (Math. sin (frequency2 * I + phase2) * width + center );
Var blue = Math. floor (Math. sin (frequency3 * I + phase3) * width + center );
Console. log ('red: '+ decimalToHex (red ));
Console. log ('green: '+ decimalToHex (green ));
Console. log ('Blue: '+ decimalToHex (blue ));
Var div = $ ('<div class = "colorBlock"> </div>'); div.css ('background-color', '#' +
DecimalToHex (red) + decimalToHex (green) + decimalToHex (blue ));
$ ('# Colors'). append (div );
}
}
We need to remove the console. log function. These calls are very bad, because each execution calls the decimalToHex function, which means that the decimalToHex function will be called twice more times. This function greatly changes the DOM structure. Each cycle adds a new div to the div with the id of colors. This makes me suspect that this is what e. extend. mergefunction does. Use the Performance Analyzer for a small experiment.
I want to add all the divs at a time, instead of adding a new div in each loop. Create a variable to store the data and add it to the variable at the last time.
Function makeColorSorter (frequency1, frequency2, frequency3, phase1, phase2, phase3, center, width, len ){
Var colors = "";
For (var I = 0; I <len; ++ I ){
Var red = Math. floor (Math. sin (frequency1 * I + phase1) * width + center );
Var green = Math. floor (Math. sin (frequency2 * I + phase2) * width + center );
Var blue = Math. floor (Math. sin (frequency3 * I + phase3) * width + center );
Colors + = '<div class = "colorBlock" style = "background-color: #' +
DecimalToHex (red) + decimalToHex (green) + decimalToHex (blue) + '">
</Div> ';
}
$ ('# Colors'). append (colors );
}
This small change means that the DOM only changes once when all divs are added. Using the time series for testing, we found that it took 31 MS from click to rendering. This dom change reduces the running time of the fourth version by 86%. I can open the Performance Analyzer (profiler) again and find that the e. extend. merge function takes a very small amount of time, which is invisible to the list.
We can also completely remove the decimalToHex function to make the code faster. Because CSS supports RGB colors, we do not need to convert them to hexadecimal notation. Now we can write the makeColorSorter function in this way.
Function makeColorSorter (frequency1, frequency2, frequency3, phase1, phase2, phase3, center, width, len ){
Var colors = "";
For (var I = 0; I <len; ++ I ){
Var red = Math. floor (Math. sin (frequency1 * I + phase1) * width + center );
Var green = Math. floor (Math. sin (frequency2 * I + phase2) * width + center );
Var blue = Math. floor (Math. sin (frequency3 * I + phase3) * width + center );
Colors + = '<div class = "colorBlock" style = "background-color: rgb (' + red + ','
+ Green + ',' + blue + ') "> </div> ';
}
$ ('# Colors'). append (colors );
}
The execution of version 5 took only 26 milliseconds and the number of lines of code reduced from 28 to 18.
Perform Javascript Performance Analysis in your application
In actual work, the application is much more complicated than the "color sequencer", but performance analysis must follow the same basic principles.
1. Set a baseline so that you know where you started.
2. isolate the problem from other codes of the application.
3. Optimization in a controllable environment, frequent use of time series (timelines) and Performance Analyzer (profiles)
There are also some performance optimization principles
1. Starting from the slowest part, the time optimization can be maximized.
2. control environment. If you change your computer or make any major changes, you must set a new baseline.
3. perform multiple analyses to prevent incorrect results due to exceptions on your computer.
Everyone wants his website to be faster. You must develop new functions, but new functions usually make the website slower. Therefore, it is valuable to spend time optimizing performance.
Performance Analysis and Optimization reduce the execution time of the final color classifier by 92%. How fast can your website become?
Zack Grossbart, compilation: bole online -- Wang Yu
Source: bole online
Note:For more information about website construction skills, go to the website creation tutorial channel.