[英]Fastest way to search ASCII files in C# for simple keywords?
现在,我在ASCII文件中搜索这样的简单关键字:
int SearchInFile (string file, string searchString)
{
int num = 0;
StreamReader reader = File.OpenText (file);
string line = reader.ReadLine();
while (line != null)
{
int count = CountSubstrings(line, searchString);
if (count != 0)
{
num += count;
}
line = reader.ReadLine();
}
reader.Close();
return num;
}
这是最快,最有效的内存方式吗? 返回计数是可选的,如果它将在搜索方式上产生巨大差异,但不是单独的。
我用它像:
SearchInFile ( "C:\\text.txt", "cool" );
只需使用StreamReader的ReadToEnd方法将文本文件加载到一个大字符串中,然后使用string.IndexOf():
string test = reader.ReadToEnd();
test.indexOf("keyword")
如果你真的想要更高的性能(处理大约数百MB或GB的文件),那么你应该按照大约1k的块来读取字符串,然后对它们进行搜索,而不是逐行搜索。 尽管必须处理一些边界条件,但这应该更快。
话虽这么说,你应该应用像ANTS这样的探查器,看看这是否真的是你的瓶颈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.