PowerShell 技能连载 - 快速读取文本文件

PowerShell 有许多读取文本文件的方法,它们的性能差异很大。请自己确认一下。以下例子演示了不同的实践,并测量执行的时间。请确保例子中的路径实际存在。如果文件不存在,请选择一个大文件来测试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# make sure this file exists, or else
# pick a different text file that is
# very large
$path = 'C:\Windows\Logs\DISM\dism.log'

# slow reading line-by-line
Measure-Command {
$text = Get-Content -Path $Path
}

# fast reading entire text as one large string
Measure-Command {
$text = Get-Content -Path $Path -Raw
}

# fast reading text as string array with one
# array element per line
Measure-Command {
$text = Get-Content -Path $Path -ReadCount 0
}

# reading entire text with .NET
# no advantage over -Raw
Measure-Command {
$text = [System.IO.File]::ReadAllText($path)
}

PowerShell 技能连载 - 快速读取文本文件

http://blog.vichamp.com/2018/06/18/reading-text-files-fast-1152612330/

作者

吴波

发布于

2018-06-18

更新于

2022-07-06

许可协议

评论