简体   繁体   English

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

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

I'm playing around with C# String.Intern method and have one questions.我正在玩弄 C# String.Intern 方法并且有一个问题。 Suppose I have a program that reads a text file line by line and adds this lines to a list of strings.假设我有一个程序逐行读取文本文件并将这些行添加到字符串列表中。 Let's assume that this file consists of thousands of lines of the same string.假设这个文件由数千行相同的字符串组成。 If the text file is big enough I can see that my program consumes decent amount of RAM.如果文本文件足够大,我可以看到我的程序消耗了大量的 RAM。 Then if I use String.Intern method when I add lines to my list, consumptions of memory drops significantly and this means that string interning works fine.然后,如果我在向列表中添加行时使用 String.Intern 方法,则 memory 的消耗会显着下降,这意味着字符串实习工作正常。 Then I want to check how many strings my dotnet process has through ProcessHacker.然后我想通过 ProcessHacker 检查我的 dotnet 进程有多少个字符串。 But whether I use String.Intern or not ProcessHacker shows the same huge amount of duplicating string.但无论我是否使用 String.Intern,ProcessHacker 都会显示相同数量的重复字符串。 I expect it would show only one instance of the string since I use String.Intern.我希望它只会显示字符串的一个实例,因为我使用的是 String.Intern。

What do I miss?我想念什么?

在此处输入图像描述

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));
                }
            }
        }
    }

Every streamReader.ReadLine() will always create a new string which will be garbage collected but until GC it will exist in memory.每个streamReader.ReadLine()将始终创建一个新字符串,该字符串将被垃圾收集,但在 GC 之前它将存在于 memory 中。 Your memory consumption can drop cause String.Intern returns the system's reference to string, if it is interned;您的 memory 消耗可能会下降导致String.Intern 返回系统对字符串的引用,如果它是实习生; otherwise, a new reference to a string with the value of string and your list will consist from references to the same instance of string which was interned making the ones created by streamReader.ReadLine() available for GC.否则,对值为 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