[英]Read line by line a large text file and search for a string
我目前正在开发一个读取大约50000行文本文件的应用程序。 对于每一行,我需要检查它是否包含特定的字符串。
目前,我使用常规的System.IO.StreamReader
逐行读取我的文件。
问题在于文本文件的大小每次都会更改。 我进行了几次测试,结果发现当文件大小增加时,读取一行会花费更多的时间。
读取包含5000行的txt文件:0:40
读取包含10000行的txt文件:2:54
读取文件的时间比读取文件大2倍,需要4倍的时间。 我无法想象读取100000行文件将花费多少时间。
这是我的代码:
using (StreamReader streamReader = new StreamReader(this.MyPath))
{
while (streamReader.Peek() > 0)
{
string line = streamReader.ReadLine();
if (line.Contains(Resources.Constants.SpecificString)
{
// Do some action with the string.
}
}
}
有没有一种方法可以避免这种情况:更大的文件=更多的时间来读取一行?
尝试这个:
var toSearch = Resources.Constants.SpecificString;
foreach (var str in File.ReadLines(MyPath).Where(s => s.Contains(toSearch))) {
// Do some action with the string
}
这样可以避免在每次循环之前通过在循环之前缓存值来访问资源。 如果这样做没有帮助,请尝试基于高级字符串搜索算法(例如KMP)编写自己的Contains
。
注意:请确保使用File.ReadLines延迟读取行(与看起来类似的File.ReadAllLines
一次读取所有行不同)。
使用RegEx.IsMatch
,您应该会看到一些性能改进。
using (StreamReader streamReader = new StreamReader(this.MyPath))
{
var regEx = new Regex(MyPattern, RegexOptions.Compiled);
while (streamReader.Peek() > 0)
{
string line = streamReader.ReadLine();
if (regEx.IsMatch(line))
{
// Do some action with the string.
}
}
}
但是,请记住使用已编译的RegEx。 这是一篇不错的文章 ,其中包含一些基准测试。
编码愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.