在C#中有效地读取极大文件.目前正在使用StreamReader

Sha*_*ogs 2 c#

我有一个大小为50GB及以上的Json文件.以下是我所写的阅读Json的一小部分内容.我现在需要修改它来读取大文件.

internal static IEnumerable<T> ReadJson<T>(string filePath)
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    using (StreamReader sr = new StreamReader(filePath))
    {
        String line;
        // Read and display lines from the file until the end of
        // the file is reached.
        while ((line = sr.ReadLine()) != null)
        {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(line);
            XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max);
            var myPerson = ser.ReadObject(jsonReader);
            jsonReader.Close();

            yield return (T)myPerson;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 如果我在当前代码中构造StreamReader时指定缓冲区大小就足够了吗?
  2. 如果我错了,请纠正我.缓冲区大小基本上指定了一次从磁盘到内存读取的数据量.因此,如果File的大小为100MB,缓冲区大小为5MB,则它一次读取5MB到内存,直到读取整个文件.
  3. 假设我对第3点的理解是正确的,那么这么大的文本文件的理想缓冲区大小是多少?int.Max大小会不是一个坏主意?在64位PC中int.Max大小是2147483647.我假设缓冲区大小以字节为单位,其值约为2GB.这本身可能会耗费时间.我看起来像100MB - 300MB作为缓冲区大小.

Mar*_*ell 5

它将一次读取一行(输入文件),可能是10个字节,可能都是50GB.所以它归结为:输入文件是如何构建的?如果输入JSON有换行符其他比干净的物体之间的断裂,这有可能会真的病.

缓冲区大小可能会影响它在查找每一行结尾时读取的数量,但最终:它需要每次都找到一个换行符(至少,当前是如何写入的).