在 C# 中使用 File.ReadLines 读取 txt 文件非常慢

very slow reading of txt file using File.ReadLines in c#

我逐行读取文件并使用 entity framework 将此数据插入数据库。阅读速度很慢。该文件将近 600 万行,我需要提高文件读取性能。它是这个文件中的单词词典,我需要将这些单词插入数据库 table。下面是该文件的几行。

390201
ТАТАМИ  NOUN,inan,neut,Fixd sing,nomn
ТАТАМИ  NOUN,inan,neut,Fixd sing,gent
ТАТАМИ  NOUN,inan,neut,Fixd sing,datv
ТАТАМИ  NOUN,inan,neut,Fixd sing,accs
ТАТАМИ  NOUN,inan,neut,Fixd sing,ablt
ТАsing,gent
ОРИГАМИ NOUN,inan,neut,Fixd ТАМИ    NOUN,inan,neut,Fixd sing,loct
ТАТАМИ  NOUN,inan,neut,Fixd plur,nomn
ТАТАМИ  NOUN,inan,neut,Fixd plur,gent
ТАТАМИ  NOUN,inan,neut,Fixd plur,datv
ТАТАМИ  NOUN,inan,neut,Fixd plur,accs
ТАТАМИ  NOUN,inan,neut,Fixd plur,ablt
ТАТАМИ  NOUN,inan,neut,Fixd plur,loct

390202
ОРИГАМИ NOUN,inan,neut,Fixd sing,nomn
ОРИГАМИ NOUN,inan,neut,Fixd sing,datv
ОРИГАМИ NOUN,inan,neut,Fixd sing,accs
ОРИГАМИ NOUN,inan,neut,Fixd sing,ablt
ОРИГАМИ NOUN,inan,neut,Fixd sing,loct
ОРИГАМИ NOUN,inan,neut,Fixd plur,nomn
ОРИГАМИ NOUN,inan,neut,Fixd plur,gent
ОРИГАМИ NOUN,inan,neut,Fixd plur,datv
ОРИГАМИ NOUN,inan,neut,Fixd plur,accs

我解析该文件的代码如下:

public static void parseFileFromToSegment(int beginId, int endId)
    {
    using (var db = new Context())
    {
        string theWordFromFile;
        string wordData;
        int wordIdFromFile = 1;
        int tempWordId;

        IEnumerable<string> allFileLines = File.ReadLines(fileName);
        allFileLines = allFileLines.SkipWhile(n => n != beginId.ToString());
        foreach (string line in allFileLines)
        {
            if (string.IsNullOrEmpty(line))
                continue;
            if (!string.IsNullOrEmpty(line) && Int32.TryParse(line, out tempWordId))
            {
                if (tempWordId < beginId)
                {
                    continue;
                }
                if (tempWordId > endId) 
                    break;

                wordIdFromFile = tempWordId;
                if (wordIdFromFile % 100 == 0)
                    Console.WriteLine("Current id - " + wordIdFromFile);
                continue;
            }

            theWordFromFile = line.Substring(0, line.IndexOf('\t'));
            wordData = line.Substring(line.IndexOf('\t')).Trim();
            TheWord theWord = new TheWord { WordFormId = wordIdFromFile, word = theWordFromFile, word_form_data = wordData };

            db.TheWords.Add(theWord);
        }
        db.SaveChanges();
        Console.WriteLine("saved");
    }
}

所以阅读速度很慢。我可以做些什么来提高性能?谢谢

不是文件读取慢。这是数据库插入。

您可以使用带有 DataAdapter 的纯 ADO.NET 来插入行 (using batching) or the SQLBulkCopy class (example)。

阅读所有评论,您似乎每 20.000 "ids" 调用 parseFileFromToSegment,这可能(根据您的示例文本)每个 ID 有很多行。

所以你打电话给你的 parseFileFromToSegment 并这样做:

IEnumerable<string> allFileLines = File.ReadLines(fileName);
allFileLines = allFileLines.SkipWhile(n => n != beginId.ToString());

在每次调用时:从头开始读取,每次调用时都可能在文件中读取数百万行。

尝试只调用一次,看看它是否更快,如果你想批量保存每条 'n' 条记录,那就这样做,不要打开并阅读 [可能] 整个'n'

的每一次迭代都归档