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

本文关键字:不可能 列表 字符串 | 更新日期: 2023-09-27 17:54:08

我在c#控制台应用程序中运行代码,存储字符串列表。这段代码的目标是在1秒内创建字符串"q"的最大集合。这只是对我编程能力的一次练习,没有实际应用价值。

当我运行这段代码时,它恰好在1秒内停止,当我计算所有字符串中所有的"q"时,我得到214,870,505,313,584,这是数以百计的万亿。字符"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;
        }
    }
}

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

我读了一段时间后,字符串存储在堆和引用。由于它一遍又一遍都是相同的字符,您可能会创建数万亿对相同物理地址的引用。