Performances If vs Switch

Hello,

Sometimes, your scripts take too much time to run and clients/bosses ask you to tune your scripts to go faster. This is a common issue we all face. A while ago we saw how we can go faster if we change the type of a certain object.

Today, we will compare the performances between If and Switch statements.

Performances If vs Switch – Code Example :

#if.ps1
$Even = 0
$Odd = 0

$list | % {
    if($_.Value -eq 1){$Odd++}
    if($_.Value -eq 2){$Even++}
    if($_.Value -eq 3){$Odd++}
    if($_.Value -eq 4){$Even++}
    if($_.Value -eq 5){$Odd++}
    if($_.Value -eq 6){$Even++}
}

Remove-Variable Odd
Remove-Variable Even
#Switch.ps1
$Even = 0
$Odd = 0

$list | % {
    switch ($a)
    {
        1            {$Odd++;break}
        2            {$Even++; break}
        3            {$Odd++;break}
        4            {$Even++; break}
        5            {$Odd++;break}
        6            {$Even++; break}
    }
        
}

Remove-Variable Odd
Remove-Variable Even

#ElseIf.ps1
$Even = 0
$Odd = 0

$list | % {
    if($_.Value -eq 1){$Odd++}
    elseif($_.Value -eq 2){$Even++}
    elseif($_.Value -eq 3){$Odd++}
    elseif($_.Value -eq 4){$Even++}
    elseif($_.Value -eq 5){$Odd++}
    elseif($_.Value -eq 6){$Even++}
}

Remove-Variable Odd
Remove-Variable Even
Performances If Vs Switch

Performances If Vs Switch

Now, we need to run those scripts a few time to be sure about the measured performances :

$list  = 1..100000 | % {
    New-Object -TypeName PSObject -Property @{Name="Odd";Value=1}
    New-Object -TypeName PSObject -Property @{Name="Event";Value=2}
    New-Object -TypeName PSObject -Property @{Name="Odd";Value=3}
    New-Object -TypeName PSObject -Property @{Name="Event";Value=4}
    New-Object -TypeName PSObject -Property @{Name="Odd";Value=5}
    New-Object -TypeName PSObject -Property @{Name="Event";Value=6}
}

Measure-ExecutionTime -Expressions {.if.ps1},{.elseif.ps1},{.switch.ps1} -Run 100

The “Measure-ExecutionTime” will run each expression 100 times, skip the worst and best duration, and then make an average of the remaining.

Result :

Performances If Vs Switch

Performances If Vs Switch

As you can see, the performances impacts between the 3  approach is not very important. The time is expressed in seconds, the maximum delta is ~17 seconds for 100 000 objects. You won’t win a lot of performances by switching between those script words.

Leave a Reply