When you write
string str="samplestring";
compiler will generate two instructions:
- Firstly,
ldstr
gets a string literal from the metadata; allocates the requisite amount of memory; creates a new String
object and pushes the reference to it onto the stack.
- Then
stloc
(or one of it's short forms, e.g. stloc.0
) stores that reference in the local variable str
.
Note, that ldstr
will allocate memory only once for each sequence of characters.
So in example below both variables will point at 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. So the contents of a String
object cannot be changed after the object is created. That is, every time you're concatenating string, CLR will create a new String
object.
For example, the following lines of code:
string a = "abc";
string b = a + "xyz";
Will be compiled into the following IL (not exactly, of course):
ldstr
will allocate memory and create a new String
object from "abc"
literal
stloc
will store the reference to that object in the local variable a
ldloc
will push that reference onto the stack
ldstr
will allocate memory and create a new String
object from "xyz"
literal
call
will invoke the System.String::Concat
on these String
objects on the stack
- A call to
System.String::Concat
will be decomposed into dozens of IL instructions and internal calls. Which, in short, will check lengths of both strings and allocate the requisite amount of memory to store the concatenation result and then copy those strings into the newly allocated memory.
stloc
will store the reference to the newly created string in the local variable b
int
. .NET doesn't have the primitive types that Java has, classes and structs all derive fromobject
.