The problem is that ToString() will still allocate a new string, and then intern it. If the garbage collector doesn't run to collect those "temporary" strings, then the memory usage will be the same.
Also, the length of your strings are pretty short. 10,000 strings that are mostly only one character long is a memory difference of about 20KB which you're probably not going to notice. Try using longer strings (or a lot more of them) and doing a garbage collect before you check the memory usage.
Here is an example that does show a difference:
class Program
{
static void Main(string[] args)
{
int n = 100000;
if (args[0] == "1")
WithIntern(n);
else
WithoutIntern(n);
}
static void WithIntern(int n)
{
var list = new List<string>(n);
for (int i = 0; i < n; i++)
{
for (int k = 0; k < 10; k++)
{
list.Add(string.Intern(new string('x', k * 1000)));
}
}
GC.Collect();
Console.WriteLine("Done.");
Console.ReadLine();
}
static void WithoutIntern(int n)
{
var list = new List<string>(n);
for (int i = 0; i < n; i++)
{
for (int k = 0; k < 10; k++)
{
list.Add(new string('x', k * 1000));
}
}
GC.Collect();
Console.WriteLine("Done.");
Console.ReadLine();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…