繁体   English   中英

如何优化此方法?

[英]How can I optimize this method?

我想优化以下方法,该方法返回指定文件夹和所有子文件夹的文件总数,以提高速度和内存使用率。 任何建议表示赞赏。

谢谢。

private int countfiles(string srcdir)
{
    try
    {
        DirectoryInfo dir = new DirectoryInfo(srcdir);

        //if the source dir doesn't exist, throw an exception
        if (!dir.Exists)
            throw new ArgumentException("source dir doesn't exist -> " + srcdir);

        int count = dir.GetFiles().Length;

        //loop through each sub directory in the current dir
        foreach (DirectoryInfo subdir in dir.GetDirectories())
        {
            //recursively call this function over and over again
            count += countfiles(subdir.FullName);
        }

        //cleanup
        dir = null;

        return count;
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
        return 0;
    }           
}

因此,我对提出的建议进行了一些基准测试。 这是我的发现:

  • 我的递归方法是在6.234秒内在目录树中找到9062个文件最慢。

  • @Matthew的答案使用SearchOption.AllDirectories,是在4.546秒内最快找到相同的9062个文件的答案

  • 使用LINQ的@Jeffery的答案在文件包的中间,可以在5.562秒内找到相同的9062文件。

谢谢大家的建议。

您能否将整个方法更改为:

int count = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length;

对我来说看起来不错,但是我将使用LINQ表达式来获取计数。

尝试这个:

int count = dir.GetFiles().Length + dir.GetDirectories().Sum(subdir =>countfiles(subdir.FullName));

希望有帮助!

我过去使用这里描述的方法,它显示了有递归和没有递归,没有递归的更快。 希望这可以帮助 ;-)

如何:遍历目录树

如果有例外,您的用户最终可能会看到许多消息框,因为每个呼叫都可能显示一个。 我将合并它们,允许用户取消该操作,或者将其一直返回到初始调用方。

如果使用的是.NET 4.0,则速度会稍快一些,但速度不会很快。

static int RecurCount(string source)
{
    int count = 0;

    try
    {
        var dirs = Directory.EnumerateDirectories(source);
        count = Directory.EnumerateFiles(source).Count();

        foreach (string dir in dirs)
        {
            count += RecurCount(dir);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return count;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM