代码之家  ›  专栏  ›  技术社区  ›  Joan Venge

在C#中搜索简单关键字的ASCII文件的最快方法?

  •  2
  • Joan Venge  · 技术社区  · 14 年前

    现在,我在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" );
    
    3 回复  |  直到 10 年前
        1
  •  5
  •   Oleg    14 年前

    在非托管代码中,性能方面最有效的方法是 Memory-Mapped Files 而不是读取缓冲区中的文件。我确信只有这样才能获得最好的结果,特别是如果要扫描的文件可能是来自远程存储的文件(来自服务器的文件)。

    我不确定相应的.NET 4.0的使用 classes 在你的情况下同样有效。

        2
  •  4
  •   Peter Mortensen icecrime    10 年前

    只需使用StreamReader的 ReadToEnd 方法并使用string.IndexOf():

    string test = reader.ReadToEnd();
    
    test.indexOf("keyword")
    
        3
  •  1
  •   Reinderien    14 年前

    如果您真的需要更高的性能(处理大小约为数百MB或GB的文件),那么不应该逐行搜索,而应该按块读取字符串(可能为1k),并对其进行搜索。尽管必须处理一些边界条件,但这应该证明得更快。

    这就是说,你应该应用一个像蚂蚁一样的分析器,看看这是否是你的瓶颈。