Badgerati / Pode

Pode is a Cross-Platform PowerShell web framework for creating REST APIs, Web Sites, and TCP/SMTP servers
https://badgerati.github.io/Pode
MIT License
830 stars 92 forks source link

Change "New-Object" calls to be ":new()" instead, for performance gain #1361

Open Badgerati opened 1 month ago

Badgerati commented 1 month ago

Describe the Change

Using New-Object to create objects is a lot slower than using :new(). For example:

(Measure-Command {
    1..1000 | % {
        $null = New-Object 'System.Collections.Generic.Stack[System.Object]'
    }
}).TotalMilliseconds

(Measure-Command {
    1..1000 | % {
        $null = [System.Collections.Generic.Stack[Object]]::new()
    }
}).TotalMilliseconds

Returns the following results on PS7.4.3:

Iterations New-Object :new()
100 25ms 2ms
1,000 190ms 5ms
10,000 1,700ms 35ms
100,000 18,500ms 250ms

Therefore, :new() should be used over New-Object.

HeyItsGilbert commented 1 month ago

Thoughts on putting together a common set of PSScriptAnalyzer rules for Pode instances? Detecting New-Object should be pretty straight forward and I'm sure there are several other common detections we'd want. I'd be happy to help make that.