C#字符串实习 [英] c# string interning

查看:128
本文介绍了C#字符串实习的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解串实习和为什么似乎并不在我的示例工作。本实施例的点是表示实施例1使用较少(少了很多存储器),因为它应该只有在存储器10中的字符串。然而,在这两个例子下面的代码中使用的大致内存(虚拟大小和工作集)是相同的。



请指教为什么例子1没有使用少了很多记忆?谢谢



例1:

 的IList<串>名单=新名单,LT;串>(10000); 

的for(int i = 0; I< 10000;我++)
{
的for(int k = 0; K< 10; k ++)
{
list.Add(中的String.intern(k.ToString()));
}

}

Console.WriteLine(实习生完成);
到Console.ReadLine();



例2:

 的IList<串GT;名单=新名单,LT;串>(10000); 

的for(int i = 0; I< 10000;我++)
{
的for(int k = 0; K< 10; k ++)
{
list.Add(k.ToString());
}

}

Console.WriteLine(实习生完成);
到Console.ReadLine();


解决方案

从的 MSDN 二,实习生字符串,必须先创建的字符串。由String对象所使用的内存仍然必须进行分配,即使内存终将被垃圾收集。


I am trying to understand string interning and why is doesn't seem to work in my example. The point of the example is to show Example 1 uses less (a lot less memory) as it should only have 10 strings in memory. However, in the code below both example use roughly the same amount of memory (virtual size and working set).

Please advice why example 1 isn't using a lot less memory? Thanks

Example 1:

        IList<string> list = new List<string>(10000);

        for (int i = 0; i < 10000; i++)
        {
            for (int k = 0; k < 10; k++)
            {
                list.Add(string.Intern(k.ToString()));
            }

        }

        Console.WriteLine("intern Done");
        Console.ReadLine();

Example 2:

        IList<string> list = new List<string>(10000);

        for (int i = 0; i < 10000; i++)
        {
            for (int k = 0; k < 10; k++)
            {
                list.Add(k.ToString());
            }

        }

        Console.WriteLine("intern Done");
        Console.ReadLine();

解决方案

From the msdn Second, to intern a string, you must first create the string. The memory used by the String object must still be allocated, even though the memory will eventually be garbage collected.

这篇关于C#字符串实习的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆