C # is a common language. Here we mainly introduce C # StringBuilder and String, including StringBuilder, which is the best choice for many String concatenation or frequent operations on a String, do not use String or other features.
C #Difference between StringBuilder and String
A new instance is generated when String operations (such as value assignment and concatenation) are performed, while StringBuilder does not. Therefore, it is best to use StringBuilder when splicing a large number of strings or frequently performing operations on a String. Do not use String
In addition, we have to say a few words about StringBuilder and String:
1. It is a reference type and memory is allocated on the stack.
2. A new instance is generated during the operation.
3. Immutable)
4. Define equal operators (= and! =) Is used to compare the value of a String object (not a reference ).
C #StringBuilder and String examples:
- Using System;
- Using System. Collections. Generic;
- Using System. Text;
- Namespace Example22
- {
- Class Program
- {
- Static void Main (string [] args)
- {
- Const int cycle= 10000;
- Long vTickCount = Environment. TickCount;
- String str = null;
- For (int I = 0; I< Cycle; I ++)
- Str + = I. ToString ();
- Console. WriteLine ("String: {0} MSEL", Environment. TickCount-vTickCount );
- VTickCount = Environment. TickCount;
- // I am angry when I see this variable name. Why do everyone make it? :)
- StringBuilder sb = new StringBuilder ();
- For (int I = 0; I< Cycle; I ++)
- Sb. Append (I );
- Console. WriteLine ("StringBuilder: {0} MSEL", Environment. TickCount-vTickCount );
- String tmpStr1 = "";
- String tmpStr2 = tmpStr1;
- Console. WriteLine (tmpStr1 );
- Console. WriteLine (tmpStr2 );
- // Note that the value of tmpStr1 does not affect the value of tmpStr2.
- TmpStr1 = "B ";
- Console. WriteLine (tmpStr1 );
- Console. WriteLine (tmpStr2 );
- Console. ReadLine ();
- }
- }
- }