performance - 在 Powershell 中,为什么查找所有目录名称比将所有文件大小相加要慢得多?
问题描述
我对这些命令中的一个与另一个相比慢了多少感到困惑。
此命令通过递归查找 C:\ 中每个子文件夹的大小来查找 C:\ 驱动器的大小
$len = 0
gci -path C:\ -recurse -force -ErrorAction SilentlyContinue | % { $len += $_.length}
此命令通过递归查看 C:\ 驱动器上的每个文件夹来查找 C:\ 驱动器上每个文件夹的名称
$result = gci -path C:\ –recurse -force -directory -ErrorAction SilentlyContinue | %{$_.fullName}
为什么第一个比第二个快那么多?文件夹大小是否有某种缓存?这仅仅是字符串操作比整数操作慢几个数量级的问题吗?
解决方案
注意:正如您所写的第一个命令会发出一堆错误消息,我取消了该命令,因为它运行了几分钟!尽管目录具有长度属性,但它是完整目录路径的长度,而不是目录的大小(以字节为单位)。
The property 'length' cannot be found on this object. Verify that the property
exists.
At line:2 char:68
+ ... ecurse -force -ErrorAction SilentlyContinue | % { $len += $_.length}
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], PropertyNotFoundException
+ FullyQualifiedErrorId : PropertyNotFoundStrict
所以我添加了 -File 开关参数。
PS> $len = 0
Measure-Command -Expression {
gci -path C:\ -File -recurse -force -ErrorAction SilentlyContinue | % { $len += $_.length}}
TotalSeconds : 58.5945269
PS> $len = 0
Measure-Command -Expression {
$x = gci -path C:\ -File -recurse -force -ErrorAction SilentlyContinue
ForEach ($File in $x) { $Len += $file.length}
}
TotalSeconds : 48.99365
正如您所看到的,使用 Pipe 比保存到变量(在这种情况下为数组)然后从那里进行处理要慢得多。我编辑了 Measure-Command 输出的冗余信息
在第二个命令中,您不只处理文件目录(-Directory),并且您不计算大小,从而使其更快。如您所见,此命令仅返回目录路径的字符串数组。(为简洁起见再次编辑)。
PS> $result.count
118148
PS> $result[0] | gm
TypeName: System.Stri
Name MemberType Definition
---- ---------- ----------
Chars ParameterizedProperty char Chars(int index) {get;}
Length Property int Length {get;}
PS> $result[0].Length
14
PS> $result[0]
C:\$GetCurrent
高温高压
推荐阅读
- r - 如何手动更改 ggplot2 图例以包含 vlines?
- python - 在pygame中发生一定数量的碰撞后更改背景
- javascript - 使用条件计算数组中的总和
- report - Adobe Analytics 服务器调用显示 eVar 和道具,但报告未捕获结果
- javascript - 从 ISO 字符串时刻 JS 库更新日期或时间
- python - TypeError:“follow_symLinks”是此函数的无效关键字参数
- java - 应用自定义哈希函数时如何读取文件
- reactjs - 在反应中通过地图更新开关状态渲染
- python - 我正在尝试使用 Python 中的指数平滑来预测数据。然而,在拟合模型后, Forecast() 不接受步骤作为参数
- pine-script - 难以向 Pine 脚本添加警报