-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
Type of issue
Typo
Feedback
Maybe something to add as a performance consideration:
(Related: PowerShell/PowerShell#25720)
Prevent unnecessarily collection comparisons
The PowerShell comparison operators have a nice feature:
When the left-hand value in the expression is a collection, the operator returns the elements of the collection that match the right-hand value of the expression.
This might come at hand if you want to filter a collection, e.g.:
$Collection = 1..99
$Collection -like '*1*' # Yields: 1 10 11 12 13 14 15 16 17 18 19 21 31 41 51 61 71 81 91
But in case it is used in a conditional statement or cmdlet that is only supposed to act on the converted boolean result, it might exceed it goal.
Take for example:
if ($Collection -like '1*') { 'Found' }
At the first item that contains a "1"
, it is already determined that the result is true, yet the whole collection is evaluated and than converted to true. Therefore you might consider to work around this feature if it concerns a large collection and an intense comparison.
One way to do this would be:
if ($Collection.where({ $_ -like '1*' }, 'first')) { 'Found' }
In this command line, the where
method will stop evaluating the rest of the collection after the first match is found. For a million items, this specific comparion is about 25 times faster.
Page URL
Content source URL
Author
Platform Id
319d7280-c701-6893-7caf-ea95ae00e437
Document Id
9818d91b-8c5f-337a-f5e1-7a40abd5fd1a