Skip to content

Instantly share code, notes, and snippets.

@santisq
Created May 7, 2022 23:21
Show Gist options
  • Select an option

  • Save santisq/ea071431bb243e17bfc237b153279886 to your computer and use it in GitHub Desktop.

Select an option

Save santisq/ea071431bb243e17bfc237b153279886 to your computer and use it in GitHub Desktop.
comparing or vs chained if vs switch
$props = 0..4 | ForEach-Object { "Prop$_"}
$i = 0
$dataset = foreach($z in 0..10000) {
$tmp = @{}
$props.foreach{ $tmp[$_] = $null }
$tmp[$props[$i++ % $props.Count]] = $z
[pscustomobject] $tmp
}
0..10 | ForEach-Object {
Measure-Command {&{
$test = $dataset
foreach($x in $test) {
if($x.Prop0) { $x }
elseif($x.Prop1) { $x }
elseif($x.Prop2) { $x }
elseif($x.Prop3) { $x }
elseif($x.Prop4) { $x }
}
}} | Select-Object @{N='Test';E={'Chained Conditions'}}, TotalMilliseconds
Measure-Command {&{
$test = $dataset
switch($test) {
{ $_.Prop0 } { $_; continue }
{ $_.Prop1 } { $_; continue }
{ $_.Prop2 } { $_; continue }
{ $_.Prop3 } { $_; continue }
{ $_.Prop4 } { $_ }
}
}} | Select-Object @{N='Test';E={'Enumerating Switch'}}, TotalMilliseconds
Measure-Command {&{
$test = $dataset
foreach($x in $test) {
switch($x) {
{ $_.Prop0 } { $_; break }
{ $_.Prop1 } { $_; break }
{ $_.Prop2 } { $_; break }
{ $_.Prop3 } { $_; break }
{ $_.Prop4 } { $_ }
}
}
}} | Select-Object @{N='Test';E={'Condition Switch'}}, TotalMilliseconds
Measure-Command {&{
$test = $dataset
foreach($x in $test) {
if($x.Prop0 -or $x.Prop1 -or $x.Prop2 -or $x.Prop3 -or $x.Prop4) { $x }
}
}} | Select-Object @{N='Test';E={'OR Conditions'}}, TotalMilliseconds
} | Group-Object Test | ForEach-Object {
[pscustomobject]@{
Test = $_.Name
Average = [System.Linq.Enumerable]::Average([int[]] $_.Group.TotalMilliseconds)
}
} | Sort-Object Average
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment