Q: Why is string connection so slow?
Let's take a look at the following section.Code:
VaR Str = 'Abc ';
Str + = 'Def ';
The system has done the following work behind this Code:
1. Allocate corresponding memory areas for 'abc' and store them;
2. Allocate a memory area of the corresponding size for 'def 'and store it;
3. allocate memory areas of the corresponding size for 'abcdef' and copy 'abc' and 'def' from their respective memory areas to the new memory areas.
As you can see, the root cause of the problem is that the memory area of the stored string cannot be changed at will. In this way, each time a string is connected, you must first allocate a storage region for the result string, and then copy each substring from its memory region to the new memory region, such complex operations will undoubtedly cause serious performance problems.
Basic Ideas
In fact, it is very simple to put all the substrings in the string into an array using the push () method of array, and finally get the final string through the join () method.
Method 1-Traditional Method (execution time:172 Ms)
VaR Str = "" ;
For ( VaR I = 0 ; I < 10000 ; I ++ ) {
Str+ = "ABC";
}
Method 2-Array method (execution time:62 Ms)
VaR Str = "" ;
VaR Arr = New Array ();
For ( VaR I = 0 ; I < 10000 ; I ++ ) {
Arr. Push ("ABC");
}
Str = Arr. Join ('');
We can see that the code execution efficiency of the second method has been greatly improved. After careful analysis, we will find that method 2 reduces the memory allocation steps compared with method 1, therefore, the performance has been greatly improved.
(Note: The code execution time comes from the author's test environment, which may vary depending on the actual situation .)
Complete code
1. Define the stringbuilder class
// Constructor
Function Stringbuilder () {
This. _ Strings= NewArray ();
}
// Append method definition
Stringbuilder. Prototype. append = Function (STR) {
This. _ Strings. Push (STR );
}
// Tostring method definition
Stringbuilder. Prototype. tostring = Function () {
Return This. _ Strings. Join ('');
}
2. Use the stringbuilder class
VaR Sb = New Stringbuilder (); // Create a stringbuilder class instance
SB. append ('abc ');
SB. append ('def ');
Alert (sb. tostring ()); // Output 'abcdef'
Summary
This article simulates stringbuilder in. Net by using the Object-Oriented function in Javascript. In order to optimize the character string connection performance, the array method is used for operations.