首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >逐行读取文本文件的最快方法是什么?

逐行读取文本文件的最快方法是什么?
EN

Stack Overflow用户
提问于 2011-11-07 21:24:58
回答 8查看 508.7K关注 0票数 357

我想逐行阅读一个文本文件。我想知道我是否在.NET C#范围内尽可能高效地完成了这项工作。

这就是我到目前为止一直在尝试的:

代码语言:javascript
复制
var filestream = new System.IO.FileStream(textFilePath,
                                          System.IO.FileMode.Open,
                                          System.IO.FileAccess.Read,
                                          System.IO.FileShare.ReadWrite);
var file = new System.IO.StreamReader(filestream, System.Text.Encoding.UTF8, true, 128);

while ((lineOfText = file.ReadLine()) != null)
{
    //Do something with the lineOfText
}
EN

Stack Overflow用户

发布于 2014-07-23 21:12:44

虽然File.ReadAllLines()是读取文件的最简单的方法之一,但它也是最慢的方法之一。

如果您只想读取文件中的行,而不想做太多操作,according to these benchmarks,读取文件的最快方法是古老的方法:

代码语言:javascript
复制
using (StreamReader sr = File.OpenText(fileName))
{
        string s = String.Empty;
        while ((s = sr.ReadLine()) != null)
        {
               //do minimal amount of work here
        }
}

然而,如果你必须对每一行做很多事情,那么this article的结论是最好的方法如下(如果你知道你要读多少行,那么预先分配一个string[]会更快):

代码语言:javascript
复制
AllLines = new string[MAX]; //only allocate memory here

using (StreamReader sr = File.OpenText(fileName))
{
        int x = 0;
        while (!sr.EndOfStream)
        {
               AllLines[x] = sr.ReadLine();
               x += 1;
        }
} //Finished. Close the file

//Now parallel process each line in the file
Parallel.For(0, AllLines.Length, x =>
{
    DoYourStuff(AllLines[x]); //do your work here
});
票数 37
EN
查看全部 8 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8037070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档