-
Notifications
You must be signed in to change notification settings - Fork 292
Avoid New-Object #60
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
Comments
I think that the use |
What I mean above is that What the article points out is that We could also make this case generically for any type that has a default/empty constructor, since you can then cast a hashtable to them. And of course (as you wrote in the linked issue), we could make that case for calling the constructor using the In the general case, you should avoid |
I understand your point and completely agree with the ins and outs related to this issue (and the one I mentioned). Anyways, what I mean was that the PowerShell Practice And Style Guide might include some (more general) guidance about the use of the I understand also that this differs from your initial request, so let me know if you think it might make more sense to open a new issue for this instead. |
You are right that it would be worthwhile making the general recommendation as well. I have changed the original post to reflect what I would propose... |
Uh oh!
There was an error while loading. Please reload this page.
In modern PowerShell, you should almost always avoid
New-Object
, because it is much slower than other methods of creating objects, like using the constructor directly via::new(
or casting a hash-table. Both the[PSObject]::new()
constructor and casting are supported in all actively supported versions of PowerShell.As always, there are some exceptions to this rule, such as when you need to create a type from a string input, or need to create a ComObject, and you may sometimes get more readable code, such as when you need to pass arguments to the constructor as well as property values.
It's also worth pointing out there is at least one special case: hash tables. PowerShell's normal hash tables, created with literal
@{ key = "value" }
syntax, are case insensitive, but hash tables created via constructor syntax[hashtable]::new()
orNew-Object Hashtable
use the .NET default case sensitive hash tables.The text was updated successfully, but these errors were encountered: