Analysis on AJAX client response speed improvement

Source: Internet
Author: User

In theory, AJAX can greatly reduce the waiting time for user operations and save data traffic on the network. However, this is not always the case. Users often complain that AJAX is used to reduce the response speed.
I have been engaged in AJAX research and development for many years and participated in the development of the more mature AJAX platform-dorado in China. Based on my experience, the root cause of this result is not AJAX. In many cases, the reduction of system response speed is caused by inadequate interface design and inefficient programming habits. Next we will analyze several steps that require constant attention during AJAX development.
Rational use of client programming and remote process calls
Client programming is mainly based on JavaScript. While JavaScript is an interpreted programming language, it runs less efficiently than Java and so on. At the same time, JavaScript runs in a strictly restricted environment such as the browser. Therefore, developers should have a clear understanding of the logic that can be executed on the client.
How to use client programming in practical applications depends on the experience of developers. A lot of questions here are only acceptable. Due to limited space, here we will summarize the following considerations:
Avoid frequent use of remote process calls as much as possible, for example, avoid using remote process calls in the loop body.
If possible, use AJAX Remote Procedure Call (asynchronous Remote Procedure Call ).
Avoid placing heavyweight data operations on the client. For example, a large volume of data replication operations, computing that requires a large amount of data traversal, and so on.
Improve the DOM object operation method.
In client programming, operations on DOM objects are usually the most likely to take up CPU time. For DOM object operations, performance differences between different programming methods are often very large.
The following three pieces of code have identical running results. They are used to create a 10 x table on the webpage. However, their operation speed is quite different. Copy codeThe Code is as follows:/* test code 1-time consumed: 41 seconds */
Var table = document. createElement ("TABLE ");
Document. body. appendChild (table );
For (var I = 0; I <1000; I ++ ){
Var row = table. insertRow (-1 );
For (var j = 0; j <10; j ++ ){
Var cell = objRow. insertCell (-1 );
Cell. innerText = "(" + I + "," + j + ")";
}
}
/* Test code 2-time consumed: 7.6 seconds */
Var table = document. getElementById ("TABLE ");
Document. body. appendChild (table );
Var tbody = document. createElement ("TBODY ");
Table. appendChild (tbody );
For (var I = 0; I <1000; I ++ ){
Var row = document. createElement ("TR ");
Tbody. appendChild (row );
For (var j = 0; j <10; j ++ ){
Var cell = document. createElement ("TD ");
Row. appendChild (cell );
Cell. innerText = "(" + I + "," + j + ")";
}
}
/* Test code 3-time consumed: 1.26 seconds */
Var tbody = document. createElement ("TBODY ");
For (var I = 0; I <1000; I ++ ){
Var row = document. createElement ("TR ");
For (var j = 0; j <10; j ++ ){
Var cell = document. createElement ("TD ");
Cell. innerText = "(" + I + "," + j + ")";
Row. appendChild (cell );
}
Tbody. appendChild (row );
}
Var table = document. getElementById ("TABLE ");
Table. appendChild (tbody );
Document. body. appendChild (table );

The difference between "test code 1" and "test code 2" is that different API methods are used when creating table cells. The difference between "test code 2" and "test code 3" is that the processing order is slightly different.
We cannot analyze the performance difference between "test code 1" and "test code 2". Currently, we know that insertRow and insertCell are table-specific APIs in DHTML, createElement and appendChild are native APIs of W3C DOM. The former should be an encapsulation of the latter. However, we cannot conclude that the native API of DOM is always better than the API specific to objects. We recommend that you perform some basic tests on the performance of an API when you need to call it frequently.
The performance difference between "test code 2" and "test code 3" mainly comes from their different build sequence. "Test code 2" first creates the <TABLE> objects on the outermost layer, and then creates <TR> and <TD> in the loop. The practice of "test code 3" is to first build the entire table from the memory to the outside, and then add it to the webpage. The purpose is to minimize the number of page la s that the browser recalculates. Every time we add an object to a webpage, the browser will try to recalculate the layout of the controls on the page. Therefore, if we can first create all the objects to be constructed in the memory, and then add them to the web page at one time. Then, the browser will only perform a re-calculation of the layout. In a word, the later the appendChild is executed, the better. Sometimes, to improve the running efficiency, we can even use removeChild to remove existing controls from the page, construct them, and place them back to the page.
Increase the string accumulation speed
When Using AJAX to submit information, I may often need to assemble some large strings to complete POST submission through XmlHttp. Although the process of submitting such large information does not seem elegant, sometimes we may have to face such a demand. So how quickly does JavaScript accumulate strings? Let's first do the following experiment. Accumulate a string of 30000 characters.Copy codeThe Code is as follows:/* test code 1-time consumed: 14.325 seconds */
Var str = "";
For (var I = 0; I <50000; I ++ ){
Str + = "xxxxxx ";
}

This Code takes 14.325 seconds and the results are not satisfactory. Now we can change the code to the following format:Copy codeThe Code is as follows:/* test code 2-time consumed: 0.359 seconds */
Var str = "";
For (var I = 0; I <100; I ++ ){
Var sub = "";
For (var j = 0; j <500; j ++ ){
Sub + = "xxxxxx ";
}
Str + = sub;
}

This Code took 0.359 seconds! In the same result, we only assemble small strings and then assemble them into larger strings. This method can effectively reduce the data volume of memory replication at the end of string assembly. After understanding this principle, we can further split the above Code for testing. The following code takes only 0.140 seconds.Copy codeThe Code is as follows:/* test code 3-time consumed: 0.140 seconds */
Var str = "";
For (var i1 = 0; i1 <5; i1 ++ ){
Var str1 = "";
For (var i2 = 0; i2 <10; i2 ++ ){
Var str2 = "";
For (var i3 = 0; i3 <10; i3 ++ ){
Var str3 = "";
For (var i4 = 0; i4 <10; i4 ++ ){
Var str4 = "";
For (var i5 = 0; i5 <10; i5 ++ ){
Str4 + = "xxxxxx ";
}
Str3 + = str4;
}
Str2 + = str3;
}
Str1 + = str2;
}
Str + = str1;
}

However, the above approach may not be the best! If the information to be submitted is in XML format (in most cases, we can try to group the information to be submitted into XML format ), we can also find more efficient and elegant methods-using DOM objects to assemble strings for us. The following code takes 950015 seconds to assemble a string with a length of 0.890.Copy codeThe Code is as follows:/* use DOM object assembly information-time consumed: 0.890 seconds */
Var xmlDoc;
If (browserType = BROWSER_IE ){
XmlDoc = new ActiveXObject ("Msxml. DOMDocument ");
}
Else {
XmlDoc = document. createElement ("DOM ");
}
Var root = xmlDoc. createElement ("root ");
For (var I = 0; I <50000; I ++ ){
Var node = xmlDoc. createElement ("data ");
If (browserType = BROWSER_IE ){
Node. text = "xxxxxx ";
}
Else {
Node. innerText = "xxxxxx ";
}
Root. appendChild (node );
}
XmlDoc. appendChild (root );
Var str;
If (browserType = BROWSER_IE ){
Str = xmlDoc. xml;
}
Else {
Str = xmlDoc. innerHTML;
}

Avoid DOM object memory leakage
Memory leakage of DOM objects in IE is often ignored by developers. However, it has very serious consequences! It causes the memory usage of IE to continue to rise, and the overall running speed of the browser is significantly reduced. For webpages with severe leaks, the operation speed may be doubled as long as they are refreshed several times.
Common Memory leakage models include "circular reference model", "Closure Function Model", and "DOM Insertion Sequence Model". For the first two leak models, we can avoid this by removing the reference during web page analysis. For the "DOM Insertion Sequence Model", you need to change some conventional programming habits to avoid this.
More information about the memory leakage model can be quickly found by Google. This article does not elaborate too much. However, here I recommend a small tool used to find and analyze Web page memory leaks-Drip. The latest version is 0.5, which is http://outofhanwell.com/ieleak/index.php.
Multipart loading and initialization of complex pages
For some interfaces in the system that are complex and inconvenient to use IFrame, we can implement multipart loading. For example, for the multi-page tag interface, we can first download and initialize the tags page of the Multi-page tag, and then use the AJAH (asynchronous JavaScript and HTML) technology to asynchronously load the content in other tabs. In this way, the interface can be displayed to the user first. Distribute the loading process of the entire complex interface to the user's operation process.
Use GZIP to compress network traffic
In addition to the code-level improvements mentioned above, we can also use GZIP to effectively reduce network traffic. Currently, common mainstream browsers all support the GZIP algorithm. We usually only need to write a small amount of code to support GZIP. For example, in J2EE, we can use the following code in the Filter to determine whether the client browser supports the GZIP algorithm, and then use java.util.zip. GZIPOutputStream as needed to implement GZIP output.Copy codeThe Code is as follows:/* code used to determine how the browser supports GZIP */
Private static String getGZIPEncoding (HttpServletRequest request ){
String acceptEncoding = request. getHeader ("Accept-Encoding ");
If (acceptEncoding = null) return null;
AcceptEncoding = acceptEncoding. toLowerCase ();
If (acceptEncoding. indexOf ("x-gzip")> = 0) return "x-gzip ";
If (acceptEncoding. indexOf ("gzip")> = 0) return "gzip ";
Return null;
}

Generally, GZIP can have a compression ratio of about 80% for HTML and JSP, which causes almost negligible performance loss on the server and client. Based on other factors, websites that support GZIP may save us 50% of network traffic. Therefore, the use of GZIP can significantly improve the performance of applications whose network environment is not particularly good. The Http monitoring tool Fiddler can be used to conveniently detect the amount of communication data before and after GZIP. (Fiddler is http://www.fiddlertool.com/fiddler)
The performance optimization of Web applications is a very big topic. Due to limited space, this article only involves several details, and cannot fully display the optimization methods of these details. We hope this article will attract everyone's attention to Web applications, especially client performance optimization. After all, the Server programming skills have been well known for many years, and the potential for performance mining on the server is no longer great. The method improvements on the client often provide amazing performance improvements.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.