Bas*_*sie 3 powershell performance if-statement switch-statement
我有以下代码If块,该代码块是我正在重写的登录脚本中的代码块:
If ($distinguishedname -match 'Joe Bloggs') {
Map-Drive 'X' "\\path\to\drive"
}
If ($distinguishedname -match 'Steve Bloggs') {
Map-Drive 'X' "\\path\to\drive"
}
If ($distinguishedname -match 'Joe Jobs') {
Map-Drive 'X' "\\path\to\drive"
}
Run Code Online (Sandbox Code Playgroud)
显然,它需要重新编写为一条If/Else语句(因为每个用户只有一个名称!)但是,我更喜欢以下switch -Regex方法的外观:
switch -Regex ($distinguishedname) {
'Joe Bloggs' {Map-Drive 'X' "\\path\to\drive"; break}
'Steve Bloggs' {Map-Drive 'X' "\\path\to\drive"; break}
'Joe Jobs' {Map-Drive 'X' "\\path\to\drive"; break}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是-以这种方式使用开关会对该功能的性能产生影响吗?它必须比上面的(if/if/if)更好,因为不是每次都评估每种可能性,但是会switch比ifelse/ifelse/else?更快。
我编写了此测试,以检查是否可以确定使用哪种方法更好Measure-Command:
function switchtest {
param($name)
switch -Regex ($name) {
$optionsarray[0] {
Write-host $name
break
}
$optionsarray[1] {
Write-host $name
break
}
$optionsarray[2] {
Write-host $name
break
}
$optionsarray[3] {
Write-host $name
break
}
$optionsarray[4] {
Write-host $name
break
}
default { }
}
}
function iftest {
param($name)
If ($name -match $optionsarray[0]) {Write-host $name}
ElseIf ($name -match $optionsarray[1]) {Write-host $name}
ElseIf($name -match $optionsarray[2]) {Write-host $name}
ElseIf($name -match $optionsarray[3]) {Write-host $name}
ElseIf($name -match $optionsarray[4]) {Write-host $name}
}
$optionsarray = @('Joe Bloggs', 'Blog Joggs', 'Steve Bloggs', 'Joe Jobs', 'Steve Joggs')
for ($i=0; $i -lt 10000; $i++) {
$iftime = 0
$switchtime = 0
$rand = Get-Random -Minimum 0 -Maximum 4
$name = $optionsarray[$rand]
$iftime = (Measure-Command {iftest $name}).Ticks
$switchtime = (Measure-Command {switchtest $name}).Ticks
Add-Content -Path C:\path\to\outfile\timetest.txt -Value "$switchtime`t$iftime"
}
Run Code Online (Sandbox Code Playgroud)
结果
平均而言,这是每个功能在10,000个测试中的执行方式:
开关-11592.8566
IfElse-15740.3281
结果并不是最一致的(有时switch更快,有时ifelse更快),但switch总体上更快(平均而言),我将使用它代替ifelse。
感谢您对此决定和我的测试的任何反馈。