繁体   English   中英

通过 ProcessHacker 方法检查 C# String.Intern 方法的工作

[英]Checking work of C# String.Intern method through ProcessHacker

我正在玩弄 C# String.Intern 方法并且有一个问题。 假设我有一个程序逐行读取文本文件并将这些行添加到字符串列表中。 假设这个文件由数千行相同的字符串组成。 如果文本文件足够大,我可以看到我的程序消耗了大量的 RAM。 然后,如果我在向列表中添加行时使用 String.Intern 方法,则 memory 的消耗会显着下降,这意味着字符串实习工作正常。 然后我想通过 ProcessHacker 检查我的 dotnet 进程有多少个字符串。 但无论我是否使用 String.Intern,ProcessHacker 都会显示相同数量的重复字符串。 我希望它只会显示字符串的一个实例,因为我使用的是 String.Intern。

我想念什么?

在此处输入图像描述

static void Main(string[] args)
    {
        List<string> list = new List<string>();
        string filePath = @"C:\Users\User\Desktop\1.txt";

        using (var fileStream = File.OpenRead(filePath))
        {
            using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
            {
                String line;
                while ((line = streamReader.ReadLine()) != null)
                {
                    list.Add(line);
                    //list.Add(String.Intern(line));
                }
            }
        }
    }

每个streamReader.ReadLine()将始终创建一个新字符串,该字符串将被垃圾收集,但在 GC 之前它将存在于 memory 中。 您的 memory 消耗可能会下降导致String.Intern 返回系统对字符串的引用,如果它是实习生; 否则,对值为 string 的字符串的新引用和您的list将由对同一字符串实例的引用组成,该实例被实习,使streamReader.ReadLine()创建的那些可用于 GC。

var str = "Test"; // compile time constant will be interned by default
var str1 = new string(str.ToArray()); // simulate reading string
Console.WriteLine(object.ReferenceEquals(str1, string.Intern(str1))); // prints false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM