gpt4 book ai didi

c# - 以最少的内存消耗将文本文件解析为列表

转载 作者:行者123 更新时间:2023-11-30 20:21:33 27 4
gpt4 key购买 nike

我有一个包含 1.000.000 行的文本文件,如下所示:

texta   text1   text#
text% text9 textx
text' text^ text3

它的大小为 19.000.000 字节...在 Windows 资源管理器中约为 18.5 MB。

我需要“在内存中”操作此文件,并以最少的内存占用对其执行 Linq 查询。这是我为测试而创建的一个应用程序,在加载约 18.5 MB 的文件后,它占用了约 47MB 的内存。这是注释的代码:

namespace ConsoleApplication1
{
public class FileClass
{
public string Field1 { get; set; }
public string Field2 { get; set; }
public string Field3 { get; set; }
}

class Program
{
static void Main(string[] args)
{
//Current Memory Heap Size: ~91 KB
List<FileClass> fileClass = new List<FileClass>();

//Current Memory Heap Size: ~172 KB
foreach (string line in File.ReadLines("c:\\somewhere\\My19000KBFile.txt"))
{
string[] linepart = line.Split('\t');
fileClass.Add(new FileClass()
{
Field1 = linepart[0],
Field2 = linepart[1],
Field3 = linepart[2]
});
}

//After bringing file in memory
//Current Memory Heap Size: ~47,000 KB
}
}
}

关于如何将此类文件放入内存,将其解析为 List<Class> 的任何想法不占用这么大的内存空间?

最佳答案

如果将整个文件读入内存,然后再处理,内存压力会很难降低。

首先,在您的断点处,如果没有通过读取文件内容进行垃圾回收,则内存中至少有 18.5 MB x 2。那已经是 37 MB。

其次,.NET 中的 string 有一点开销,就像您创建的类一样。这意味着你在这里也会有一些内存损失。

Jon Skeet 写了一篇 blog article关于在 C# 中优化内存中的字符串。了解您如何丢失一些内存以及如何优化字符串操作可能对您有用。

关于c# - 以最少的内存消耗将文本文件解析为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33779926/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com