Skip to content

Prevent unnecessarily collection comparisons #12212

@iRon7

Description

@iRon7

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

https://learn.microsoft.com/en-us/powershell/scripting/dev-cross-plat/performance/script-authoring-considerations?view=powershell-7.5

Content source URL

https://github.com/MicrosoftDocs/PowerShell-Docs/blob/main/reference/docs-conceptual/dev-cross-plat/performance/script-authoring-considerations.md

Author

@sdwheeler

Platform Id

319d7280-c701-6893-7caf-ea95ae00e437

Document Id

9818d91b-8c5f-337a-f5e1-7a40abd5fd1a

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions