AJAX Client Response speed improvement Analysis _ajax related

Source: Internet
Author: User
Theoretically, Ajax technology can reduce the waiting time of the user's operation and save the data traffic on the network to a great extent. However, the reality is not always the case. Users often complain that the AJAX system responds less quickly.
The author engaged in the research and development of Ajax for many years, participated in developing the current domestic more mature Ajax platform-dorado. According to the author's experience, the root cause of this result is not in Ajax. Most of the time, the reduction of system response speed is caused by unreasonable interface design and less efficient programming habits. Let's look at some of the aspects of Ajax development that need to be noticed all the time.
Reasonable use of client-side programming and remote procedure calls
The client's programming is primarily JavaScript based. While JavaScript is an interpreted programming language, its efficiency is lesser relative to Java. JavaScript is also running in a strictly restricted environment such as a browser. So developers should have a clear understanding of what logic can be executed on the client side.
How to use client-side programming in practical applications depends on the experience of the developer. Many of the problems here are sensed. Due to the limited space, here we have summed up the following several points of attention:
Avoid using remote procedure calls as frequently as possible, such as avoiding the use of remote procedure calls in the loop body.
If possible, use AJAX-style remote procedure calls (asynchronous, remote procedure calls) whenever possible.
Avoid placing heavyweight data operations on the client. For example: large-scale data replication operations, the need for a large number of data traversal completed calculations.
Improve the way you manipulate DOM objects.
In client programming, the manipulation of Dom objects is often the easiest to consume CPU time. For the operation of Dom objects, the performance differences between different programming methods are often very large.
The following are the exact same code for the three-part run, which is to create a 10x1000 table in the Web page. But they run at a different speed.
Copy Code code as follows:

/* Test Code 1-time consuming: 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 < J + +) {
var cell = Objrow.insertcell (-1);
Cell.innertext = "(" + i + "," + j + ")";
}
}
/* Test Code 2-time consuming: 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 < J + +) {
var cell = document.createelement ("TD");
Row.appendchild (cell);
Cell.innertext = "(" + i + "," + j + ")";
}
}
/* Test Code 3-time consuming: 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 < 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" Here is that different API methods are used when creating table cells. The difference between "test code 2" and "Test Code 3" is a slightly different processing order.
There is so much performance difference between "test code 1" and "Test code 2" that we don't have an analysis, and now we know that InsertRow and Insertcell are unique to the forms in DHTML Api,createelement and AppendChild are the The native API for the DOM. The former should be encapsulated in the latter. However, we cannot conclude that Dom's native APIs are always superior to object-specific APIs. It is recommended that you do some basic testing on the performance of an API when you need to call it frequently.
The performance difference between "test code 2" and "Test Code 3" comes mainly from a different build order. The practice of "Test Code 2" is to create the outermost <TABLE> object first, and then create <TR> and <TD> sequentially in the loop. The "test Code 3" approach is to first build the entire table in memory from inside to outside, and then add it to the Web page. This is done to minimize the number of times the browser recalculates the page layout. Whenever we add an object to a Web page, the browser attempts to recalculate the layout of the controls on the page. So if we can first create all the objects in memory and then add them to the page again. Then, the browser will only do a layout recalculation once. summed up as a word that is the more late execution appendchild the better. Sometimes in order to improve efficiency, we can even consider using RemoveChild to remove the existing controls from the page, and then put them back in the page after the construction is complete.
Increase the speed of string accumulation
When submitting information using AJAX, I may often need to assemble some larger strings to complete post submissions through XMLHTTP. While the practice of submitting such a large message does not look elegant, sometimes we may have to face this demand. So what is the cumulative speed of strings in JavaScript? Let's do the following experiment first. Add a string that is 30000 long.
Copy Code code as follows:

/* Test Code 1-time consuming: 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 ideal. Now let's change the code to the following form:
Copy Code code as follows:

/* Test Code 2-time consuming: 0.359 seconds * *
var str = "";
for (var i = 0; i < i++) {
var sub = "";
for (var j = 0; J < j) {
Sub + = "xxxxxx";
}
str = SUB;
}

This code takes 0.359 seconds! As a result, we're just assembling some smaller strings and then assembling them into larger strings. This approach can effectively reduce the amount of memory replicated data later in the string assembly. Knowing this principle, we can further disassemble the above code and test it later. The following code takes only 0.140 seconds.
Copy Code code as follows:

/* Test Code 3-time consuming: 0.140 seconds * *
var str = "";
for (var i1 = 0; i1 < 5; i1++) {
var str1 = "";
for (var i2 = 0; i2 < i2++) {
var str2 = "";
for (var i3 = 0; i3 < i3++) {
var str3 = "";
for (var i4 = 0; i4 < i4++) {
var str4 = "";
for (var i5 = 0; i5 < i5++) {
STR4 + = "xxxxxx";
}
STR3 + = STR4;
}
STR2 + = STR3;
}
STR1 + = str2;
}
str = STR1;
}

However, the above approach may not be the best! If the information we need to submit is in XML format (in most cases we can manage to assemble the information to be submitted in an XML format), we can also find a more efficient and elegant way to assemble strings for us using DOM objects. The following generation to assemble a string of length 950015 takes only 0.890 seconds.
Copy Code code as follows:

/* Use DOM objects to assemble information-time consuming: 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 memory leaks from DOM objects
Memory leaks of DOM objects in IE are a problem that is often overlooked by developers. However, the consequences of it are very serious! It can cause IE's memory footprint to continue to rise, and the overall operating speed of the browser has dropped significantly. For some of the more serious leakage of the Web page, even as long as the refresh several times, the running speed will be reduced by one times.
The more common models for memory leaks are "circular reference Model", "Closure function model", and "DOM insert Order Model", and for the first two models, we can avoid them by releasing the references in the Web page destructor. The DOM Insert Order model, however, needs to be avoided by changing some of the usual programming habits.
More information about the model of memory leaks can be found quickly through Google, this article does not do too much elaboration. However, here I recommend you a gadget that can be used to find and analyze Web page memory leaks--drip, the newer version is 0.5, and the download address is http://outofhanwell.com/ieleak/index.php.
Segmented loading and initialization of complex pages
For some of the systems that are actually more complex and inconvenient to use the IFRAME, we can implement a segmented load on them. For example, for a multi-page label interface, we can first download and initialize the default page for multiple-page labels, and then use Ajah (asynchronous JavaScript and HTML) technology to asynchronously load the contents of other tabs. This ensures that the interface can be first presented to the user at the first time. The loading process of the whole complex interface is dispersed into the user's operation process.
Compress network traffic with gzip
In addition to the code-level improvements mentioned above, we can also use GZIP to effectively reduce network traffic. The most common mainstream browsers already support the GZIP algorithm, we often need to write a small number of code to support gzip. For example, in Java EE we can use the following code in the filter to determine whether the client browser supports the GZIP algorithm, and then utilize java.util.zip.GZIPOutputStream to implement GZIP output as needed.
Copy Code code as follows:

/* Determine the browser's code for the GZIP support mode * *
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;
}

In general, Gzip for HTML, JSP compression ratio can reach about 80%, and it caused by the server and client performance loss can be almost negligible. Combined with other factors, the website that supports gzip may save us 50% of network traffic. As a result, the use of gzip can lead to significant performance improvements for applications that do not have a particularly good network environment. Using the HTTP monitoring Tool fiddler can easily detect the amount of traffic data that the Web page uses before and after using gzip. (Fiddler's download Address is http://www.fiddlertool.com/fiddler/)
Performance optimization for Web applications is really a big topic. Due to its limited space, this article can only be involved in a few of the details, and can not be the optimization of these details to fully show the way. It is expected that this paper can arouse the attention to the Web application, especially the client performance optimization. After all, the service-side programming skills have been known for many years, and the potential for mining performance at the server side has been limited. Improvements in the client approach can often be surprisingly performance-enhancing.
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.