Performance 切换vs If Else性能
我在重新编写的登录脚本中有以下Performance 切换vs If Else性能,performance,powershell,if-statement,switch-statement,Performance,Powershell,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
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"
}
显然需要将其重新编写为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}
}
我的问题是-以这种方式使用交换机会对该功能的性能产生任何影响吗?它必须比上面的(
if/if/if
)更好,因为不是每次都评估每个可能性,但是开关是否会比ifelse/ifelse/else
更快,switch语句通过在汇编代码中构建跳转表来工作,并使用跳转表来确定适当的路由,而不是使用if/else之类的比较器。这就是switch语句更快的原因。我相信,对于字符串,编译器会生成字符串的哈希代码,并使用该代码实现跳转表,从而使switch语句更快。因此,switch语句应该比上面写的if/if/if快,但可能不是这样,因为switch语句通常依赖于间隔稍均匀的选项(例如1 2 3或5 10 15)
既然如此,为什么不使用if/elseif/elseif来代替if/if/if呢?这肯定会更快,因为不是每次都对每个选项进行评估。我编写此测试是为了检查是否可以使用测量命令找出哪种方法更好:
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"
}
结果
平均而言,这是每个功能在10000次测试中的执行方式:
开关-11592.8566
IfElse-15740.3281
结果并不是最一致的(有时switch
更快,有时ifelse
更快),但由于switch
总体上更快(平均而言),我将使用它而不是ifelse
如果您对我的决定和测试有任何反馈,我们将不胜感激。您确定这同样适用于像PowerShell这样的动态/解释性语言吗?您如何为支持正则表达式模式匹配的交换机实现基于哈希的跳转表?@Ryan感谢您的回答。基于一些测试,我决定选择开关
(参见我自己的答案)。您认为这些测试是确定哪个语句更快的有效方法吗?您可能希望使用组而不是逐个测试用户,但我的测试不适用于您的situation@sodawillow感谢您的评论-我正在脚本的其他地方测试组,但是这里执行的设置对于这些用户来说是独一无二的,所以这似乎是我的最佳方式