[英]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.