I have a question about string creation in a loop following is a code sample:
static void Main(string[] args)
{
for (int i = 1; i <= 1000000; i++)
{
Add(GetStr());
}
Console.WriteLine("hmmmmmmmm");
Console.ReadLine();
}
public static string GetStr()
{
return "OK";
}
public static void Add(string str)
{
list.Add(str);
}
How many number of strings will be created in memory in case of above code ???
How many number of strings will be created in memory in case of above code
One. (or actually two if you include "hmmmmmmmm"
)
This method returns a constant string literal:
public static string GetStr()
{
return "OK";
}
It is compiled into something like the following IL code:
ldstr "OK"
ret
The LDSTR opcode will push a reference to a string literal stored in metadata and the RET opcode will return that reference.
This means that "OK"
will only be allocated once in the metadata. All entries in the list will refer to that instance.
Notice that string literals are interned by default. So no "temporary string" will be allocated before being interned and therefore no garbage collection is needed.
I have modified your code so that you can see the Memory addrese of the string "OK"
using System;
namespace ConsoleApplication4
{
using System.Collections.ObjectModel;
public class Program
{
static unsafe Collection<string> list = new Collection<string>();
static unsafe void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
Add(GetStr());
}
foreach (var str in list)
{
fixed (char* ptr = str)
{
var addr = (IntPtr)ptr;
Console.WriteLine(addr.ToString("x"));
}
}
Console.WriteLine("hmmmmmmmm");
Console.ReadLine();
}
public unsafe static string GetStr()
{
return "OK";
}
public unsafe static void Add(string str)
{
list.Add(str);
}
}
}
------------ Console Output ------------------------
As you see the list use the same memory reference for the string "Ok".
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
#225bf54
hmmmmmmmm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With