When you write
string str="samplestring";
Compiler
generates two commands:
- First,
ldstr gets a string literal from metadata; allocates the required amount of memory; creates a new String object and pushes a link to it on the stack. - Then
stloc (or one of its short forms, for example stloc.0 ) stores this link in the local variable str .
Note that ldstr will allocate memory only once for each character sequence.
So, in the example below, both variables will point to the same object in memory:
// CLR will allocate memory and create a new String object // from the string literal stored in the metadata string a = "abc"; // CLR won't create a new String object. Instead, it will look up for an existing // reference pointing to the String object created from "abc" literal string b = "abc";
This process is known as string interning .
Also, as you know, in .NET strings are immutable. Thus, the contents of the String object cannot be changed after the creation of the object. That is, every time you concatenate a string, the CLR will create a new String object.
For example, the following lines of code:
string a = "abc"; string b = a + "xyz";
It will be compiled into the following IL (not really, of course):
ldstr will allocate memory and create a new String object from "abc" literalstloc store the reference to this object in the local variable aldloc will push this link ldloc stackldstr will allocate memory and create a new String object from "xyz" literalcall will call System.String::Concat for these String objects on the stack- The
System.String::Concat will be decomposed into dozens of IL statements and internal calls. Which, in short, will check the lengths of both lines and allocate the required amount of memory to store the result of the concatenation, and then copy these lines to the newly allocated memory. stloc save the link to the newly created line in local variable b
source share