In many operations with the same string, using the stringbuilder class is more efficient than using the string object. The string data type represents an unchangeable string. The only way to insert, delete, or modify a string is to create a new string, this will lead to configuration operations on the memory and anti-configuration operations on the memory, which will increase the CLR management memory and memory recovery. This situation is more obvious, especially when operating large strings, in a single user environment, there will be no problems, but in a server environment, performance and scalability will cause serious problems. And system. compared to string, stringbuilder retains its own string buffer. When performing string operations on stringbuilder, it first checks whether the buffer size can accommodate new strings, when it is not enough, it will increase the amount of memory required. Therefore, the number of memory configuration operations is greatly reduced and the efficiency is improved. Of course, in most cases, it is better to estimate more buffer space than to continue to increase later.
Below I will use a small example to reveal the differences between the two of them, so that you can more intuitively feel their performance differences... (not an order of magnitude)
This is a 10 million execution operations. Compared with the time spent by the two companies, stringbuilder has almost no time, and string has to charge 24 seconds. If it is a single-Host Program, it may be okay, if it is in the server environment, the impact of this efficiency is very obvious. below is the code I tested .....
String STR = "hello ";
Stringbuilder sb = new stringbuilder ();
Double first;
First = system. environment. tickcount;
For (INT I = 0; I <100000; I ++)
{
STR + = "NT ";
}
First = environment. tickcount-first;
Console. writeline ("string consume time --" + first );
First = environment. tickcount;
For (INT I = 0; I <100000; I ++)
{
SB. append ("NT ");
}
First = environment. tickcount-first;
Console. writeline ("stringbuilder consume time --" + first );
Console. Readline ();
I just summarized some of my experiences and shared them with you, hoping to benefit from them ....