大字符串列表应该是不可能的

Gan*_*ing 2 c# compression string list

我在C#控制台应用程序中运行代码,该应用程序存储字符串列表.此代码的目标是在1秒内尽可能创建字符串"q"的最大集合.这只是我编程能力的练习,没有实际应用.

当我运行这段代码时,它会在1秒内停止运行,当我计算所有字符串中的所有"q"时,我得到214,870,505,313,584,这是数百万亿.char"q"占用一个字节,如果这个东西有200万亿字节,则意味着字符串列表超过2TB.

这怎么可能,是否有某种自动压缩?有没有办法把它关掉?

如果你愿意,这是代码.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ConsoleAppWebScrape
{
    class Program
    {
        //the origional string
        static string l = "q";
        static DateTime d;
        static List<string> output = new List<string>();

        static void Main(string[] args)
        {
            //hit enter to start
            Console.Read();
            d = DateTime.Now;

            //start the string doubling thread
            Thread thred2 = new Thread(new ThreadStart(doubleL));
            thred2.Start();
            //start the write to list thread                                                                                               
            Thread thred1 = new Thread(new ThreadStart(writeToFile));
            thred1.Start();

            while (haveTime())
            {
               //pause current thread for the remander of the second. 
            }

            long lo = howmany();

            Console.WriteLine(lo);
            Console.ReadLine();
        }

        //determines the amount of "q"s in the list of strings
        static long howmany()
        {
            long lo = 0;
            foreach (string s in output)
            {
                lo += s.Length;
            }
            return lo;
        }
        //writes to the list of strings.
        static void writeToFile()
        {
            while (haveTime())
            {
                output.Add(l);
            }
        }
        //builds a string by doubling the origional string
        static bool tobig = false;
        static void doubleL()
        {
            while (haveTime() && !tobig)
            {
                if (l.Length < 268435456)
                {
                    l = l + l;
                }
                else
                {
                    tobig = true;
                }
            }
        }
        //bool to determin if it is running inside one second
        static bool haveTime()
        {
            if ((DateTime.Now - d).TotalSeconds < 1)
            {
                return true;
            }
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

我已经读过一段时间,字符串存储在堆上并被引用.由于它一遍又一遍地使用相同的字符,因此您可能会创建数万亿个对同一物理地址的引用.