.NET / C # compile will not be able to determine the strings in the string scratch pool is recycled garbage out GC

When we no longer use an object, the object can be recycled garbage off the GC. Of course, the premise is you do not have to write code to memory leaks. We also know that if a large number of string is generated, the GC will cause a lot of pressure.

However, if during compilation to determine the string, it will not be recovered GC garbage out.

Sample Code

Next, I created a few strings, string my concern is  "walterlv" ,  "lindexi" and a current time.

Then use the following code to verify:

using System;
using System.Linq;
using System.Runtime.CompilerServices;

namespace Walterlv.Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            var table = new ConditionalWeakTable<string, Foo>
            {
                {"walterlv", new Foo("吕毅")},
                {"lindexi", new Foo("林德熙")},
            };
            var time = DateTime.Now.ToString("T");
            table.Add(time, new Foo("时间"));
            time = null;

            Console.WriteLine($"开始个数:{table.Count()}");
            GC.Collect();
            Console.WriteLine($"The remaining number: table.Count {()} "); 
        }
    }

    public class Foo
    {
        public string Value { get; }
        public Foo(string value) => Value = value;
    }
}

"walterlv" And  "lindexi" it is fully determined at compile time string, the string and the current time we all know can not be determined at compile time string.

GC before and after collection,  ConditionalWeakTable the number of objects from three down to two.

And it is not cleared to 0, indicating that the string is still cited significant.

That is what references yet? String scratch pool. To understand string scratch pool, you can read my other blog post:

Further, even if provided  CompilationRelaxations.NoStringInterning , can be determined during compilation in the above code string is not be garbage collected.

Reference material

If you have wanted to learn c ++ programmers, you can come to our C / C ++ learning buckle qun: 589348389,
free delivery C ++ Video Tutorial Oh!
Each 20:00 I will live in the group to explain the C / C ++ knowledge, welcome everyone to learn Oh.

 

Guess you like

Origin blog.csdn.net/XZQ121963/article/details/90742560