Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to optimize JS code

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to optimize JS code". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to optimize JS code".

1. Concatenation of strings

String stitching is often encountered in our development, so I put it in the first place, we are often used to directly using the + = way to stitch strings, in fact, this splicing way is very inefficient, we can use an ingenious way to achieve string stitching, that is, the use of array join method.

/ inefficient function func1 () {var start = new Date (). GetTime (); var template = ""; for (var I = 0; I < 10000; iTunes +) {template + = "";} var end = new Date (). GetTime (); document.getElementById ("one") [xss_clean] = template; alert ("time:" + (end-start) + "millisecond") } / / efficient function func2 () {var start = new Date (). GetTime (); var array = []; for (var I = 0; I < 10000; iTunes +) {array [I] = "";} var end = new Date (). GetTime (); document.getElementById ("one") [xss_clean] = array.join ("") Alert ("usage:" + (end-start) + "milliseconds");}

Let's take a look at its execution in different browsers.

We will find that the difference is quite obvious under IE6, in fact, this situation is also very obvious in the high version of IE, but there is not much difference in Firefox, on the contrary, the relative efficiency of the second is a little lower, but only the difference between 2ms or so, and Chrome is also similar to Firefox. In addition, by the way, when we add elements to an array, many people like to use the native method push of the array, but it is faster to directly use arr [I] or arr [arr.length]. There will be a difference of more than ten milliseconds under the IE browser in the case of 10000 loops.

2. For cycle

The for loop is something we often encounter. Let's look at the following example:

Var arr = []; for (var I = 0; I < 10000; iBoy +) {arr [I] = "" + I + ";} document.body [XSS _ clean] + = arr.join ("); / / inefficient function func1 () {var divs = document.getElementsByTagName (" div "); var start = new Date (). GetTime (); for (var I = 0; I < divs.length) Var end = new Date (). GetTime (); alert ("usage:" + (end-start) + "milliseconds");} / / efficient function func2 () {var divs = document.getElementsByTagName ("div"); var start = new Date (). GetTime (); for (var I = 0, len = divs.length; I < len) Var end = new Date (). GetTime (); alert ("usage:" + (end-start) + "milliseconds");}

As can be seen from the above table, the difference is very obvious under IE6.0, but there is almost no difference between Firefox and Chrome. The main reason for this is that in the execution of the for loop, the length is calculated every time in the first case, while in the second case, the length is calculated at the beginning and saved in a variable, so its execution efficiency is higher. So when we use a for loop, especially if we need to calculate the length, we should start saving it in a variable. However, there is not such an obvious difference as long as we take the length. If we just manipulate an array and get the length of an array, then the two ways of writing are actually similar. Let's take a look at the following example:

Var arr2 = []; for (var I = 0; I < 10000; iTunes +) {arr2 [I] = "" + I + ";} / / inefficient function func1 () {var start = new Date (). GetTime (); for (var I = 0; I < arr2.length; I +) {/ /" inefficient "} var end = new Date (). GetTime () Alert ("usage:" + (end-start) + "milliseconds");} / / efficient function func2 () {var start = new Date () .getTime (); for (var I = 0, len = arr2.length; I < len; ionization +) {/ / "efficient"} var end = new Date () .getTime () Alert ("usage:" + (end-start) + "milliseconds");}

As can be seen from the above table, if it is just an array, we can see that the two ways of writing are actually the same. in fact, if we raise the loop to 100000 times, it is only a few milliseconds different, so in the case of an array, I think it's all the same. For the optimization of the for cycle, some people put forward a lot of points, some people think that using-= 1, or looping from big to small, and so on, I think it is completely unnecessary, these optimizations are often not shown at all in the actual situation, in other words, they are only small changes at the computer level, but what they bring to us is a great reduction in the readability of the code, so the loss outweighs the gain.

3. Reduce the redrawing of the page

Although the essence of reducing page redrawing is not the optimization of JS itself, it is often caused by JS, and the situation of page redrawing often seriously affects page performance, so it is absolutely necessary to take it out. Let's take a look at the following example:

Var str = "this is a test string" / inefficient function func1 () {var obj = document.getElementById ("demo"); var start = new Date (). GetTime (); for (var I = 0; I < 100; iBj +) {obj [XSS _ clean] + = str + I;} var end = new Date (). GetTime (); alert ("usage" + (end-start) + "millisecond") } / / highly efficient function func2 () {var obj = document.getElementById ("demo"); var start = new Date (). GetTime (); var arr = []; for (var I = 0; I < 100; iTunes +) {arr [I] = str + I;} obj [XSS _ clean] = arr.join (""); var end = new Date (). GetTime () Alert ("usage time" + (end-start) + "millisecond");}

In the example, I only used 100 loops, because if you use 10000 loops, the browser basically stays stuck, but even for 100 loops, let's take a look at the execution results below.

What you can see is that this is simply an amazing result, only 100 cycles, no matter what browser, there is such a big difference, in addition, we also found that here, the implementation efficiency of IE6 is much better than Firefox, it can be seen that Firefox does not do some optimization in page redrawing. It should also be noted here that it is not only innerHTML that generally affects page redrawing, but also triggers page redrawing if you change the style and location of elements, so you must pay attention to this at ordinary times.

4. Reduce the number of searches on the scope chain

We know that when js code executes, if it needs to access a variable or a function, it needs to traverse the scope chain of the current execution environment, and the traversal traverses backwards from the front of the scope chain to the global execution environment, so there is often a situation here, that is, if we need to access the variable objects of the global environment frequently. Every time we have to traverse one level of the current scope chain, which is obviously time-consuming, let's take a look at the following example:

Function func1 () {var start = new Date (). GetTime (); for (var I = 0; I < 10000; iTunes +) {var but1 = document.getElementById ("but1"); var but2 = document.getElementById ("but2"); var inputs = document.getElementsByTagName ("input"); var divs = document.getElementsByTagName ("div"); var but1 = document.getElementById ("but1") Var but2 = document.getElementById ("but2"); var inputs = document.getElementsByTagName ("input"); var divs = document.getElementsByTagName ("div"); var but1 = document.getElementById ("but1"); var but2 = document.getElementById ("but2"); var inputs = document.getElementsByTagName ("input"); var divs = document.getElementsByTagName ("div") Var but1 = document.getElementById ("but1"); var but2 = document.getElementById ("but2"); var inputs = document.getElementsByTagName ("input"); var divs = document.getElementsByTagName ("div"); var but1 = document.getElementById ("but1"); var but2 = document.getElementById ("but2"); var inputs = document.getElementsByTagName ("input") Var divs = document.getElementsByTagName ("div"); var but1 = document.getElementById ("but1"); var but2 = document.getElementById ("but2"); var inputs = document.getElementsByTagName ("input"); var divs = document.getElementsByTagName ("div");} var end = new Date (). GetTime (); alert ("usage" + (end-start) + "milliseconds") } function func2 () {var start = new Date (). GetTime (); var doc = document; for (var I = 0; I < 10000; iTunes +) {var but1 = doc.getElementById ("but1"); var but2 = doc.getElementById ("but2"); var inputs = doc.getElementsByTagName ("input"); var divs = doc.getElementsByTagName ("div") Var but1 = doc.getElementById ("but1"); var but2 = doc.getElementById ("but2"); var inputs = doc.getElementsByTagName ("input"); var divs = doc.getElementsByTagName ("div"); var but1 = doc.getElementById ("but1"); var but2 = doc.getElementById ("but2"); var inputs = doc.getElementsByTagName ("input") Var divs = doc.getElementsByTagName ("div"); var but1 = doc.getElementById ("but1"); var but2 = doc.getElementById ("but2"); var inputs = doc.getElementsByTagName ("input"); var divs = doc.getElementsByTagName ("div"); var but1 = doc.getElementById ("but1"); var but2 = doc.getElementById ("but2") Var inputs = doc.getElementsByTagName ("input"); var divs = doc.getElementsByTagName ("div"); var but1 = doc.getElementById ("but1"); var but2 = doc.getElementById ("but2"); var inputs = doc.getElementsByTagName ("input"); var divs = doc.getElementsByTagName ("div");} var end = new Date (). GetTime () Alert ("usage time" + (end-start) + "millisecond");}

In the above code, the second case is to first put the variable of the global object into the function, save it, and then access the variable directly, while the first case is to traverse the scope chain every time until the global environment. We see that the second case is actually traversed only once, while the first case is traversed every time, so let's take a look at the execution result:

As can be seen from the above table, the difference is still very obvious under IE6, and the difference is also very obvious in the case of multi-level scope chains and multiple global variables.

5. Avoid double interpretation

Double interpretation is also a situation that we often encounter. Sometimes we don't think much about the impact on efficiency. Double interpretation is usually encountered when we use eval, new Function and setTimeout. Let's take a look at the following example:

Var sum, num1 = 1, num2 = 2; function func1 () {var start = new Date (). GetTime (); for (var I = 0; I < 10000; iTunes +) {var func = new Function ("sum+=num1;num1+=num2;num2++;"); func ();} var end = new Date (). GetTime (); alert ("time of use" + (end-start) + "millisecond") } function func2 () {var start = new Date (). GetTime (); for (var I = 0; I < 10000; iTunes +) {sum+=num1; num1+=num2; num2++;} var end = new Date (). GetTime (); alert ("usage time" + (end-start) + "milliseconds");}

In the first case, we use new Function for double interpretation, and the second is to avoid double interpretation. Let's look at the performance in different browsers:

As you can see, in all browsers, double interpretation is very expensive, so in practice, double interpretation should be avoided.

Thanks to "SeaSunK" for correcting the error in the fourth test report, which has now been corrected. As for the func1 proposed in the last point, it is initialized every time, so I changed the eval. It turns out that there is still an impact under IE6.0, and under Firefox, the use of eval has a greater impact on efficiency. Under Firefox, if 10000 loops take more than ten seconds, so I changed the loops to 1000. Look at the code and the report.

Var sum, num1 = 1, num2 = 2; function func1 () {var start = new Date (). GetTime (); for (var I = 0; I < 1000; iTunes +) {eval ("sum+=num1;num1+=num2;num2++;");} var end = new Date (). GetTime (); alert ("time of use" + (end-start) + "milliseconds") } function func2 () {var start = new Date (). GetTime (); for (var I = 0; I < 1000; iTunes +) {sum+=num1; num1+=num2; num2++;} var end = new Date (). GetTime (); alert ("usage time" + (end-start) + "milliseconds");}

Thank you for your reading, the above is the content of "how to optimize JS code", after the study of this article, I believe you have a deeper understanding of how to optimize JS code, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report