gpt4 book ai didi

c# - 为什么 EnumerateFiles 比计算大小快得多

转载 作者:太空狗 更新时间:2023-10-29 18:35:18 24 4
gpt4 key购买 nike

对于我的 WPF 项目,我必须计算单个目录(可能有子目录)中的总文件大小。

示例 1

DirectoryInfo di = new DirectoryInfo(path);
var totalLength = di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);

if (totalLength / 1000000 >= size)
return true;

示例 2

 var sizeOfHtmlDirectory = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
long totalLength = 0;
foreach (var file in sizeOfHtmlDirectory)
{
totalLength += new FileInfo(file).Length;
if (totalLength / 1000000 >= size)
return true;
}

两个示例都有效。

示例 1 在极短的时间内完成。我没有准确计时,但在我的 PC 上,使用具有相同内容/文件大小的相同文件夹,示例 1 需要几秒钟,示例 2 需要几分钟。

编辑

我应该指出,示例 2 中的瓶颈在 foreach 循环中!它快速读取 GetFiles 并快速进入 foreach 循环。

我的问题是,我如何找出出现这种情况的原因?

最佳答案

与其他答案表明的相反,主要区别不是 EnumerateFilesGetFiles - 它是 DirectoryInfoDirectory - 在后一种情况下,您只有字符串并且必须单独创建新的 FileInfo 实例,这非常昂贵。

DirectoryInfo 返回使用缓存信息的 FileInfo 实例 vs 直接创建新的 FileInfo 实例而不是 - 更多详细信息 herehere .

相关引述(来自“The Old New Thing”):

In NTFS, file system metadata is a property not of the directory entry but rather of the file, with some of the metadata replicated into the directory entry as a tweak to improve directory enumeration performance. Functions like Find­First­File report the directory entry, and by putting the metadata that FAT users were accustomed to getting "for free", they could avoid being slower than FAT for directory listings. The directory-enumeration functions report the last-updated metadata, which may not correspond to the actual metadata if the directory entry is stale.

关于c# - 为什么 EnumerateFiles 比计算大小快得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29800121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com