本文介绍了被拘禁在.NET的垃圾收集例外字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图来减少花费的时间做了第二代集合。我的应用程序创建并持有大量的字符串对象,通过它的生命坚持的。

I am trying to reduce time it takes to do a Gen2 collection. My app creates and holds a large number of string objects, which persist through its life.

减少扫描对象的数量应该减少GC时间。我不知道实习生池是否是从垃圾收集除外。有没有什么反正那里聚集。如果是这样,我能实习生所有这些字符串,加快GC。

Reducing number of scanned objects should reduce GC time. I was wondering whether intern pool is excepted from garbage collection. There isn't anything to collect there anyway. If so, I could intern all these strings and speed up GC.

推荐答案

我做了一个快速测试和字符串的实习不似乎是由GC从扫描保存。至少在.NET 4.5 64位。

I made a quick test and interning of strings does not seem to save them from scanning by GC. At least not in .NET 4.5 64 bit.

class Program
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 20000000; ++i)
        {
            string s = i.ToString("X");
            string.Intern(s);
        }
        GC.Collect(3, GCCollectionMode.Forced, true);
        long t1 = Stopwatch.GetTimestamp();
        GC.Collect(3, GCCollectionMode.Forced, true);
        long t2 = Stopwatch.GetTimestamp();
        Console.WriteLine((double)(t2 - t1) / Stopwatch.Frequency);
    }
}

这对基准i5的一个返回3570k 0.23s。如果字符串放入数组,而不是实习,返回0.26s。如果字符串是通过(I%10)的ToString(),即有不同的实例的数量少,基准返回微秒。

This benchmark returns 0.23s on an i5 3570k. If the strings are put into an array instead of interning, it returns 0.26s. If the strings are interned and created via (i % 10).ToString(), i.e. there's a small number of different instances, the benchmark returns microseconds.

所以,可悲的是,这不是绕过垃圾收集方式。我认为C#应该有标识字符串作为持续性的一些方法和停止运行系统上扫描他们浪费时间。

So sadly this is not a way to bypass garbage collection. I think C# should have some way of marking strings as persistent and stop the runtime wasting time on scanning them.

这篇关于被拘禁在.NET的垃圾收集例外字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:51