Get the execution time of the program. In php, we add a timer at the beginning of the page to the end and then subtract the start time from the end time to the execution time of the program, this method can also be used in js.
The specific JS Code is as follows:
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> Var st = new Date (). getTime (); </Script> <P> for example, get the time here. </P> <P> Create a div here, and then. </P> <P> here we will take the time again, and then we want to subtract the two time points. You can get the execution time of this Code. The effect is as follows: </p> <Script type = "text/javascript"> Var st2 = new Date (). getTime ()-st; Document. write ("the execution time of the above three natural segments is" + st2 + "millisecond "); </Script> |
You can use this method to calculate the execution time of JavaScript code, in milliseconds.
Jquery implementation code
By comparing the js execution time, We can filter out js statements with higher execution efficiency and better performance for actual projects.
We can directly use the console. time (arg1) & console. timeEnd (arg1) method to confirm the js running time. arg1 is the parameter of this method.
Note that the 2 Statement must appear in pairs at the same time, and the parameters (both Chinese and English) must be consistent.
The Code is as follows: |
Copy code |
<Select id = "page"> </select> <Script type = "text/javascript" src = "jquery. min. js"> </script> <Script type = "text/javascript"> $ (Function (){ Console. time ('high-performance writing, execution Time'); // test the start position of js execution time. parameters are output as prefix, console. time () is the same as console. timeEnd () is used together, and the parameters must be consistent! Var $ page = $ ('# page'), option; For (var I = 1; I <1000; I ++ ){ Option + = "<option value =" + I + "> page" + I + "</option> "; } // Dom operation once $ Page. append (option ); Console. timeEnd ('high-performance writing, execution Time'); // test the js execution time end position </p> Console. time ('low-performance writing, execution Time '); Var $ page = $ ('# page ') For (var I = 1; I <1000; I ++ ){ // Dom operation 999 times $ Page. append ("<option value =" + I + "> page" + I + "</option> "); } Console. timeEnd ('low-performance writing, execution Time '); }); </Script>
|
You can use chrome or firefox debugging tools to view the actual execution time of two js sections.
Note: browsers of the ie series do not support the console. time (arg1) & console. timeEnd (arg1) method.