string

 公共语言运行时通过维护名为拘留池的表来节省字符串存储,该表包含对程序中以编程方式声明或创建的每个唯一文本字符串的单个引用。 因此,系统中仅存在一个具有特定值的文本字符串的实例。

string.Intern 是终生制的,一旦加入只要程序不重启,就会一直存在。

// Sample for String.Intern(String)
using System;
using System.Text;

class Sample
{
    public static void Main()
    {
        string s1 = "MyTest";
        string s2 = new StringBuilder().Append("My").Append("Test").ToString();
        string s3 = String.Intern(s2);
        Console.WriteLine($"Is s2 the same reference as s1?: {(Object)s2 == (Object)s1}");
        Console.WriteLine($"Is s3 the same reference as s1?: {(Object)s3 == (Object)s1}");
    }
}
/*
This example produces the following results:
Is s2 the same reference as s1?: False
Is s3 the same reference as s1?: True
*/

 

.NET 5 引入了一项运行时行为更改,其中,全球化 API 在所有支持的平台上默认使用 ICU。如果在使用 string.IndexOf(string) 这样的函数时不调用使用 StringComparison 参数的重载,则可能在计划执行序号搜索时无意中依赖于特定于区域性的行为。 由于 NLS 和 ICU 在其语言比较器中实现的逻辑有所不同,因此 string.IndexOf(string) 等方法的结果可能会返回意外的值。

const string greeting = "Hel\0lo";
Console.WriteLine($"{greeting.IndexOf("\0")}"); //0
Console.WriteLine($"{greeting.IndexOf("\0", StringComparison.Ordinal)}"); //3

如果 API 接受显式 StringComparison 或 CultureInfo 参数,则该参数将覆盖 API 的默认行为。

 

Microsoft.Toolkit.HighPerformance 包中StringPool类解决重复字符串实例过多,导致浪费内存的情况。优点是可以释放

 

posted @ 2021-11-20 16:04  yetsen  阅读(12)  评论(0编辑  收藏  举报