Similarities:
Both objects are string operations,
Differences:
String typeEach time the string is referenced, the space will be allocated again, and the originally allocated space will also exist. If you repeat the operation, it will occupy a large amount of memory space, thus wasting memory resources, such:
String str = "life ";
Str = str + "you ";
First, a str variable is defined to allocate physical memory space for the string "Lifetime,
The str value is now "you are in your life", and a physical space is also allocated in the memory to store "you have in your life", but the memory space allocated in the memory last time is "Lifetime ", it also occupies memory space.
StringBuilder classWhen referenced by an instance, strings in its original physical memory are operated and no other physical space is allocated.
Physical space operations, so there will be no signs of resource waste. For example:
StringBuilder sb = new StringBuilder ("life ");
Sb. Append ("you ");
Response. Write (sb );
Performance Comparison Between string and StringBuilder
String str = "";
StringBuilder sbstr = new StringBuilder ();
Int times = 1000;
Int end = 0, start = 0;
// Time used to test the sting
For (int I = 0; I <times; I ++)
{
Str + = I. ToString ();
}
End = Environment. TickCount;
Console. WriteLine (end-start ));
// Time used to test stringbuilder
Start = Environment. TickCount;
For (int k = 0; k <times; k ++)
{
Sbstr. Append (k. ToString ());
}
End = Environment. TickCount;
Console. WriteLine (end-start );
Console. ReadKey ();
Running result: (milliseconds used)
Str: 416670062
Sbstr: 0
Through the above analysis, we can see that the connection validity rate of strings is very low, but not all cases use StringBuilder. When we connect a few strings, we can use String, however, StringBuilder must be used for a large number or frequent string connection operations.
Learning ....