Last active
February 22, 2020 01:20
-
-
Save MysticRyuujin/6c393e6b3a9a8c40219486083fd783a8 to your computer and use it in GitHub Desktop.
PowerShell Where/Filter Speed Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Get lots of items into an Array | |
Write-Host 'Getting all files in $env:windir\system32' | |
$AllFiles = Get-ChildItem -File -Path ($env:windir+"\system32") -Recurse -ErrorAction SilentlyContinue | |
Write-Host "Found $($AllFiles.Count) files`n" | |
$Types = @( | |
"Simple Match", | |
"Where-Object Property" | |
"Where-Object ScriptBlock" | |
"Filter" | |
"Where Method" | |
"ForEach" | |
"ForEach-Object" | |
) | |
$Output = [System.Collections.Generic.List[pscustomobject]]::new() | |
ForEach ($Type in $Types) { | |
switch ($Type) { | |
"Simple Match" { | |
Write-Output 'Test: $AllFiles -match "cmd.exe"' | |
$TimeResult = Measure-Command { | |
$Files = $AllFiles -match "cmd.exe" | |
} | |
} | |
"Where-Object Property" { | |
Write-Output 'Test: $AllFiles | Where-Object name -match "cmd.exe"' | |
$TimeResult = Measure-Command { | |
$Files = $AllFiles | Where-Object name -match "cmd.exe" | |
} | |
} | |
"Where-Object ScriptBlock" { | |
Write-Output 'Test: $AllFiles | Where-Object { $_.name -match "cmd.exe" }' | |
$TimeResult = Measure-Command { | |
$Files = $AllFiles | Where-Object { $_.name -match "cmd.exe" } | |
} | |
} | |
"Filter" { | |
Write-Output 'Test: filter MyFilter { if ($_ -match "cmd.exe") { $_ } }; $AllFiles | MyFilter' | |
$TimeResult = Measure-Command { | |
filter MyFilter { if ($_ -match "cmd.exe") { $_ } } | |
$Files = $AllFiles | MyFilter | |
} | |
} | |
"Where Method" { | |
Write-Output 'Test: $AllFiles.Where({$_.name -match "cmd.exe"})' | |
$TimeResult = Measure-Command { | |
$Files = $AllFiles.Where({$_.name -match "cmd.exe"}) | |
} | |
} | |
"ForEach" { | |
Write-Output 'Test: foreach ($file in $AllFiles) { if ($File.name -match "cmd.exe") { $_ } }' | |
$TimeResult = Measure-Command { | |
$Files = foreach ($File in $AllFiles) { | |
if ($File.name -match "cmd.exe") { $File } | |
} | |
} | |
} | |
"ForEach-Object" { | |
Write-Output 'Test: $AllFiles | ForEach-Object { if ($_.name -match "cmd.exe") { $_ } }' | |
$TimeResult = Measure-Command { | |
$Files = $AllFiles | ForEach-Object { | |
if ($_.name -match "cmd.exe") { $_ } | |
} | |
} | |
} | |
} | |
$Output.Add([pscustomobject]@{ | |
"Method" = $Type | |
"TotalMilliseconds" = [math]::Round($TimeResult.TotalMilliseconds,2) | |
"Matching Files" = $Files.Count | |
}) | |
} | |
$Output | Sort-Object -Property TotalMilliseconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment