读取文本文件并以内存有效的方式搜索字符串(发现后中止) [英] read a text file and search for string in memory efficient way (and abort when found)
问题描述
我正在搜索文本文件(还包括XML)中的字符串.这是我首先想到的:
I'm searching for a string in a text file (also includes XML). This is what I thought first:
using (StreamReader sr = File.OpenText(fileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mySpecialString"))
return true;
}
}
return false;
我想逐行读取以最小化RAM的使用量.找到字符串后,应中止该操作.我之所以不将其作为XML进行处理,是因为必须对其进行解析,并且在必要时还会消耗更多的内存.
I want to read line by line to minimize the amount of RAM used. When the string has been found it should abort the operation. The reason why I don't process it as XML is because it has to be parsed and would also consume more memory as necessary.
另一个容易实现的方法是
Another easy implementation would be
bool found = File.ReadAllText(path).Contains("mySpecialString") ? true : false;
但是这会将完整的文件读入内存,这不是我想要的.另一方面,它可能会提高性能.
but that would read the complete file into memory, which isn't what I want. On the other side it could have a performance increase.
另一个是这个
foreach (string line in File.ReadLines(path))
{
if (line.Contains("mySpecialString"))
{
return true;
}
}
return false;
但是其中哪一个(或您中的另一个?)的内存使用效率更高?
But which one of them (or another one from you?) is more memory efficient?
推荐答案
You can use a query with File.ReadLines
, so it only reads as many lines as it needs to, in order to satisfy your query. The Any()
method will stop when it hits a line containing your string.
return File.ReadLines(fileName).Any(line => line.Contains("mySpecialString"));
这篇关于读取文本文件并以内存有效的方式搜索字符串(发现后中止)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!