When using Ajax to submit information, I may often need to assemble some relatively large strings to complete POST submission through XmlHttp. Although submitting such large information may seem inelegant, sometimes we may have to face such a need. So how fast is the accumulation of strings in JavaScript? Let’s do the following experiment first. Accumulate a string of length 30000.
Test code 1 - Time consumption: 14.325 seconds
var str = "";
for (var i = 0; i < 50000; i ) {
str = "xxxxxx";
}
This code takes 14.325 seconds, and the result is not ideal. Now we change the code to the following form:
Test Code 2 - Time taken: 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 takes 0.359 seconds! Same result, all we do is assemble some smaller strings first and then assemble into larger strings. This approach can effectively reduce the amount of data copied in memory in the later stages of string assembly. After knowing this principle, we can further dismantle the above code for testing. The code below only takes 0.140 seconds.
Test code 3 - Time consumption: 0.140 seconds
var strArray = new Array();
for (var i = 0; i < 100; i ) {
var sub = "";
for (var j = 0 ; j < 500; j ) {
sub = "xxxxxx";
}
strArray.push(sub);
}
str = String.prototype.concat.apply(" ", strArray);
However, the above approach may not be the best! If the information we need to submit is in XML format (in fact, in most cases, we can try to assemble the information to be submitted into XML format), we can also find a more efficient and elegant method - using DOM objects to assemble it for us string. The following paragraph only takes 0.890 seconds to assemble a string with a length of 950015.
Use DOM objects to assemble information - time consumption: 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;
}