I was looking for a way to remove empty items from an array and I couldn’t find any examples that didn’t involve Where-Object
. I did find one that is a lot faster at scale, and I haven’t seen it used, so I thought I’d share.
# The typical way '','Testing','','Something','','Neat' | Where-Object { $_ } # A faster but PowerShell V4.0+ only way ('','Testing','','Something','','Neat').Where({ $_ }) # The way I haven't seen used '','Testing','','Something','','Neat' -match '.' # Speed tests Write-Host '--------------------------------------' foreach ($rate in 1,10,100,10000) { "Where-Object ${rate}: " + (Measure-Command { for ($i = 0; $i -lt $rate; $i++) { '','Testing','','Something','','Neat' | Where-Object { $_ } } }).TotalMilliseconds + 'ms' "Where Method ${rate}: " + (Measure-Command { for ($i = 0; $i -lt $rate; $i++) { ('','Testing','','Something','','Neat').Where({ $_ }) } }).TotalMilliseconds + 'ms' "Match Operator ${rate}: " + (Measure-Command { for ($i = 0; $i -lt $rate; $i++) { '','Testing','','Something','','Neat' -match '.' } }).TotalMilliseconds + 'ms' Write-Host '--------------------------------------' } <# The results: -------------------------------------- Where-Object 1: 0.7795ms Where Method 1: 0.0858ms Match Operator 1: 0.0404ms -------------------------------------- Where-Object 10: 5.3721ms Where Method 10: 2.4548ms Match Operator 10: 0.2751ms -------------------------------------- Where-Object 100: 53.9397ms Where Method 100: 14.1568ms Match Operator 100: 1.219ms -------------------------------------- Where-Object 10000: 3290.8187ms Where Method 10000: 952.868ms Match Operator 10000: 105.9024ms -------------------------------------- #>
Edit: The race is on! Great entries so far. As a bonus, this one will filter out items that are just whitespace too, a little slower though.
'','Testing','',' Something',' ','Neat' -match '(?!^s+$).'
Results: (Different speed because on laptop)
-------------------------------------- Where-Object 100: 108.3381ms Where Method 100: 13.4863ms Match Operator 100: 8.5235ms Match NoWhitespace 100: 11.9075ms -------------------------------------- Where-Object 10000: 7540.8253ms Where Method 10000: 1079.3157ms Match Operator 10000: 295.907ms Match NoWhitespace 10000: 315.2145ms --------------------------------------
submitted by /u/SeeminglyScience
[link] [comments]
The post Removing empty items in a collection appeared first on How to Code .NET.