For more information about the connection efficiency of javascript strings, see.
String connection
1. Most Commonly Used + =
I always said that the efficiency of this method is the lowest. Why? Let's take a look at the substantive process of this method.
Var str = "hello ";
Str + = "world ";
(1) create a string that stores "hello.
(2) create a string for storing "world.
(3) create a string that stores the connection results.
(4) copy the current content of str to the result.
(5) Copy "world" to the result.
(6) Update str to point it to the result.
Each time the string connection is completed, steps 2 to 6 are executed, which consumes a lot of resources. If you repeat this process several hundred or even thousands of times, it will cause performance problems. This will be abandoned in the future, hahaha. Pai_^
Ii. join () method
The Code is as follows:
// Button call
Function JoinFn (){
Var arr = new Array;
Arr [0] = "James ";
Arr [1] = "Li Si ";
Alert (arr. join (""));
}
The procedure is as follows:
(1) create a string for storing the result.
(2) copy each string to a proper position in the result.
This method is more efficient than the first one.
3. encapsulate a custom class
JavaScript does not have the StringBuilder class as in C #, but we can customize a StringBuilder class. The method of creating a class is the "mixed constructor/prototype" mentioned in the previous article ".
The Code is as follows:
// Customize a StringBuilder class to connect strings
Function StringBuilder (){
This. _ strings = new Array ();
}
StringBuilder. prototype. append = function (str ){
This. _ strings. push (str );
};
StringBuilder. prototype. toString = function (){
Return this. _ strings. join ("");
};
// Button call
Function MyConnectClassFn (){
Var sb = new StringBuilder ();
Sb. append ("Zhang San ");
Sb. append ("Li Si ");
Var strResult = sb. toString ();
Alert (strResult );
}
Summary
Finally, compare the above three methods. The book says that the last method is the fastest, but after my tests, it seems that join () is the fastest, and the third method is the slowest, is there a problem with my custom StringBuilder class?