我如何优化这个方法
本文关键字:方法 优化 何优化 | 更新日期: 2023-09-27 18:04:11
我想优化以下方法,该方法返回指定文件夹和所有子文件夹的总文件计数,用于速度和内存使用;任何建议都很感激。
谢谢。
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。
是最快在4.546秒内找到相同的9062个文件 @Jeffery的答案,使用LINQ,在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;
}