c# string interning

前端 未结 4 2296
时光取名叫无心
时光取名叫无心 2020-12-17 19:10

I am trying to understand string interning and why is doesn\'t seem to work in my example. The point of the example is to show Example 1 uses less (a lot less memory) as it

4条回答
  •  悲&欢浪女
    2020-12-17 19:19

    The problem is that ToString() will still allocate a new string, and then intern it. If the garbage collector doesn't run to collect those "temporary" strings, then the memory usage will be the same.

    Also, the length of your strings are pretty short. 10,000 strings that are mostly only one character long is a memory difference of about 20KB which you're probably not going to notice. Try using longer strings (or a lot more of them) and doing a garbage collect before you check the memory usage.

    Here is an example that does show a difference:

    class Program
    {
        static void Main(string[] args)
        {
            int n = 100000;
    
            if (args[0] == "1")
                WithIntern(n);
            else
                WithoutIntern(n);
        }
    
        static void WithIntern(int n)
        {
            var list = new List(n);
    
            for (int i = 0; i < n; i++)
            {
                for (int k = 0; k < 10; k++)
                {
                    list.Add(string.Intern(new string('x', k * 1000)));
                }
            }
    
            GC.Collect();
            Console.WriteLine("Done.");
            Console.ReadLine();
        }
    
        static void WithoutIntern(int n)
        {
            var list = new List(n);
    
            for (int i = 0; i < n; i++)
            {
                for (int k = 0; k < 10; k++)
                {
                    list.Add(new string('x', k * 1000));
                }
            }
    
            GC.Collect();
            Console.WriteLine("Done.");
            Console.ReadLine();
        }
    }
    

提交回复
热议问题