What's the fastest way to read a text file line-by-line?

前端 未结 8 2039
情歌与酒
情歌与酒 2020-11-22 02:51

I want to read a text file line by line. I wanted to know if I\'m doing it as efficiently as possible within the .NET C# scope of things.

This is what I\'m trying so

相关标签:
8条回答
  • 2020-11-22 03:30

    There's a good topic about this in Stack Overflow question Is 'yield return' slower than "old school" return?.

    It says:

    ReadAllLines loads all of the lines into memory and returns a string[]. All well and good if the file is small. If the file is larger than will fit in memory, you'll run out of memory.

    ReadLines, on the other hand, uses yield return to return one line at a time. With it, you can read any size file. It doesn't load the whole file into memory.

    Say you wanted to find the first line that contains the word "foo", and then exit. Using ReadAllLines, you'd have to read the entire file into memory, even if "foo" occurs on the first line. With ReadLines, you only read one line. Which one would be faster?

    0 讨论(0)
  • 2020-11-22 03:34

    Use the following code:

    foreach (string line in File.ReadAllLines(fileName))
    

    This was a HUGE difference in reading performance.

    It comes at the cost of memory consumption, but totally worth it!

    0 讨论(0)
提交回复
热议问题