Skip to content

Instantly share code, notes, and snippets.

@santisq
Created June 29, 2024 14:42
Show Gist options
  • Save santisq/f1b59dfd51e0a359f733080c6c32369b to your computer and use it in GitHub Desktop.
Save santisq/f1b59dfd51e0a359f733080c6c32369b to your computer and use it in GitHub Desktop.
Invoke-RestMethod https://gist.githubusercontent.com/santisq/bd3d1d47c89f030be1b4e57b92baaddd/raw/236c79877ebaa75ce81c1806ef568d77abad6724/Measure-Expression.ps1 |
Invoke-Expression
$range = [System.Linq.Enumerable]::Range(1, 100kb)
time @{
'foreach + if' = {
param($range)
$result = foreach ($i in $range) { if ($i % 2) { $i } }
}
'.where' = {
param($range)
$result = $range.ToArray().Where({ $_ % 2 })
}
'where-object' = {
param($range)
$result = $range | Where-Object { $_ % 2 }
}
'process block + if' = {
param($range)
$result = $range | & { process { if ($_ % 2) { $_ } } }
}
'linq' = {
param($range)
$result = [System.Linq.Enumerable]::Where(
$range,
[Func[int, bool]]{param($e) $e % 2 }).
ToArray()
}
} -Parameters @{ range = $range }
Test                  Average RelativeSpeed
----                  ------- -------------
foreach + if         49.63 ms 1x
process block + if  176.45 ms 3.56x
.where              425.14 ms 8.57x
linq                557.04 ms 11.22x
where-object       1364.18 ms 27.49x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment