function Xntest () {
var d1=new date ();
var str= "";
for (Var i=0;i<10000;i++) {
str+= "Stext";
}
var d2=new date ();
document.write ("string concatenation method Time consuming:" + (D2.gettime ()-d1.gettime ()) + "milliseconds;");
D1=new date ();
var sb=new array ();
for (Var i=0;i<10000;i++) {
Sb.push ("Stext");
}
var result=sb.tostring ();
D2=new date ();
document.write ("Array mode time consuming:" + (D2.gettime ()-d1.gettime ()) + "milliseconds;");
}
Here is a brief introduction to the application
Each completion of a string connection performs steps 2 through 6, making this operation very resource-intensive. If you repeat this process hundreds of times, or even thousands of times, it can cause performance problems. The workaround is to store the string with the array object and then create the last string with the Join () method (the argument is an empty string). Imagine replacing the previous code with the following code:
Copy code code as follows:
var str=new array ();
str[0]= "Hello";
Str[1]= "World";
Str.join ("");
In this way, no matter how many strings are introduced into the array, it is not a problem because the join operation occurs only when the join () method is invoked. At this point, the following steps are performed:
(1) Create a string that stores the results.
(2) Copy each string to the appropriate location in the result.
Copy code code as follows:
function StringBuilder () {
This._string=new Array ();
}
Stringbuilder.prototype.append=function (str) {
This._string.push (str);
}
Stringbuilder.prototype.tostring=function () {
Return This._string.join ("");
}
The quickest way to string concatenation
First: adding Strings by string
Copy code code as follows:
var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...],
list = ';
for (var i = 0, L = arr.length i < l; i++) {
List + + ' <li> ' + arr[i] + ';
}
List = ' <ul> ' + list + ' </ul> ';
This is the most common, but the lowest efficiency! Code logic is relatively complex.
The second type: Push into the array one by one
Copy code code as follows:
var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...],
list = [];
for (var i = 0, L = arr.length i < l; i++) {
List[list.length] = ' <li> ' + arr[i] + ';
}
List = ' <ul> ' + list.join (') + ' </ul> ';
It's a little bit quicker than the last one, but it's not good enough ...
The third type: Direct join ()
Copy code code as follows:
var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...];
var list = ' <ul><li> ' + arr.join (' </li><li> ') + ' </li></ul> ';
Finally, take a look at string connection considerations
Try to use StringBuilder instead of normal string concatenation. But perhaps most developers have overlooked the need to pay attention to this efficiency problem JS