Reputation: 246
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 ???
Upvotes: 4
Views: 238
Reputation: 17003
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
Upvotes: 5
Reputation: 11344
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.
Upvotes: 9
Reputation: 27944
In your case there will be 2 strings created by your code: "OK" and "hmmmmmmmm". Because string a an immutable type the "OK" will only be created once, and every time you need it the string will just be referenced.
Upvotes: 2