[英]Fastest way to find text in file
所以我正在尋找一種有效搜索文件中文本的方法。 現在我正在使用這個:
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 1024, FileOptions.SequentialScan))
using (StreamReader streamReader = new StreamReader(fileStream))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
int index = 0;
while ((index = line.IndexOf(searchText, index, StringComparison.Ordinal)) != -1)
{
index += searchText.Length;
}
}
}
但是,我想知道是否有一種方法可以更有效地搜索文件。 我在想也許在緩沖區中搜索文本,但我不確定如何。 謝謝。
編輯:在不調用 IndexOf 的情況下,我得到大約 1600 毫秒。 使用索引,它大約是 7400ms。
編輯:我有一個塊讀取的基本實現,它把時間減少到 740 毫秒。 (沒有閱讀線)它仍然有很多工作,但我基本上一次閱讀一大塊並獲取索引。
從性能的角度來看,您的方法將是 O(xl) 時間,其中 x 是要搜索的字符串的長度,l 是您要查找的字符串的長度。 您可以應用的通用算法很少:
我建議您使用 Boyer-Moore,這里有關於如何實現它的示例: https://www.geeksforgeeks.org/boyer-moore-algorithm-for-pattern-searching/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.