Skip to content

New-Object 'System.Collections.Generic.List[string]' searches every loaded assembly on each call #28472

Open

Description

Prerequisites

Steps to reproduce

Measure-Command { 1..2000 | % { New-Object 'System.Collections.Generic.List[string]' } }
Measure-Command { 1..2000 | % { [System.Collections.Generic.List[string]]::new() } }

Expected behavior

I tried resolving the arity-qualified name first and falling back to the old order. Dictionary, List, HashSet, Nullable and using namespace cases resolve to the same types. Script modules that call New-Object with a generic type in a loop get faster. Expand-Archive from the Archive module bundled with 7.7.0 does that once per entry, and it got 8% and 6% faster over two runs (0.92x [0.89, 0.95] and 0.94x [0.92, 0.95]) on a 2,000-entry zip.

Actual behavior

GenericTypeName.GetReflectionType first resolves the plain name (System.Collections.Generic.List), which doesn't exist, and only then tries List`1. The type cache only keeps hits, so every New-Object 'System.Collections.Generic.List[string]' walks all loaded assemblies (and the using namespace variants) before it finds the type. [System.Collections.Generic.List[string]]::new() is about 10 times cheaper in a loop. With the change described above, one New-Object 'System.Collections.Generic.List[string]' goes from about 0.2 ms to 0.04 ms (two runs, 194 and 214 µs before, 39 and 45 µs after).

Error details

No error. It's a performance issue.

Environment data

Name                           Value
----                           -----
PSVersion                      7.6.10
PSEdition                      Core
GitCommitId                    7.6.10
OS                             Microsoft Windows 10.0.26100
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.4
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Measured on master cd071c9 (Release build), Windows 11 x64.

Visuals

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions