Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Badgerati opened this issue Jul 18, 2024 · 2 comments · Fixed by #1399
Closed

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

Badgerati opened this issue Jul 18, 2024 · 2 comments · Fixed by #1399

Comments

@Badgerati
Copy link
Owner

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.

  • All current references to New-Object should be replaced with :new() instead. Ensuring all arguments are kept the same.
  • A new test in _.Tests.ps1 to make sure there are no new references to New-Object going forward.
  • Update the Contributing.md to state :new() should be used over New-Object.
@HeyItsGilbert
Copy link

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.

@Badgerati
Copy link
Owner Author

hey @HeyItsGilbert, I've added a PSScriptAnalyzer rule for Pode itself, to detect New-Object and flag. The same can probably be done for other cmdlets found here as a different GitHub issue: https://github.com/Badgerati/Pode/blob/develop/.github/CONTRIBUTING.md#powershell-commandlets

I would imagine those custom rules in ./analyzers could then be used by other people, to help detect them in their own Pode scripts? 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging a pull request may close this issue.

2 participants