PowerShellPracticeAndStyle icon indicating copy to clipboard operation
PowerShellPracticeAndStyle copied to clipboard

Avoid New-Object

Open Jaykul opened this issue 9 years ago • 4 comments
trafficstars

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() or New-Object Hashtable use the .NET default case sensitive hash tables.

Jaykul avatar Jun 23 '16 22:06 Jaykul