1. After the String is allocated, it cannot be changed?
The following code may cause compilation errors:
String s = "hello ";
S [0] = 'a ';
This may cause:
Error 3 Property or indexer 'string. this [int] 'cannot be assigned to -- it is read only
In fact, it can be changed:
Unsafe
{
String s = "hello ";
Fixed (char * p1 = s)
{
* P1 = 'a ';
}
}
2. the String cannot be constructed using new?
Because the code
String s = new string ("hello ");
An error will be reported. There is no such ctor, but the string actually has eight cuts:
Public String (char * value );
Public String (char [] value );
Public String (sbyte * value );
Public String (char c, int count );
Public String (char * value, int startIndex, int length );
Public String (char [] value, int startIndex, int length );
Public String (sbyte * value, int startIndex, int length );
Public String (sbyte * value, int startIndex, int length, Encoding enc );
3. Will the string "+" generate a new string?
String s = "he" + "ll" + "o ";
Look at IL:
IL_0000: nop
IL_0001: ldstr "hello"
IL_0006: stloc.0
IL_0007: ret
It is actually a string, and the compiler does something we don't know.
4. Why is StringBuilder better than String?
String s = null;
For (int I = 0; I <100; I ++)
S + = I. ToString ();
+ The actual call is the String static method public static stringConcat(String str0, string str1)
Public static string Concat (string str0, string str1)
{
If (IsNullOrEmpty (str0 ))
{
If (IsNullOrEmpty (str1 ))
{
Return Empty;
}
Return str1;
}
If (IsNullOrEmpty (str1 ))
{
Return str0;
}
Int length = str0.Length;
String dest = FastAllocateString (length + str1.Length );
FillStringChecked (dest, 0, str0 );
FillStringChecked (dest, length, str1 );
Return dest;
}
The following code:
StringBuilder sb = new StringBuilder ();
For (int I = 0; I <100; I ++)
Sb. Append (I. ToString ());
Append (String) method:
Public StringBuilder Append (string value)
{
If (value! = Null)
{
String stringValue = this. m_StringValue;
IntPtr currentThread = Thread. InternalGetCurrentThread ();
If (this. m_currentThread! = CurrentThread)
{
StringValue = string. GetStringForStringBuilder (stringValue, stringValue. Capacity );
}
Int length = stringValue. Length;
Int requiredLength = length + value. Length;
If (this. NeedsAllocation (stringValue, requiredLength ))
{
String newString = this. GetNewString (stringValue, requiredLength );
NewString. AppendInPlace (value, length );
This. ReplaceString (currentThread, newString );
}
Else
{
StringValue. AppendInPlace (value, length );
This. ReplaceString (currentThread, stringValue );
}
}
Return this;
}
Comparison:
String indicates that space needs to be allocated after each concatenation and a reference to the new string is returned. StringBulder is a pre-allocated space. When concatenating strings, it first checks the space of strings and then determines whether to allocate new space.Applying for memory space from the stack is time-consuming.