Difference new-object and ::new()

Hi all,

Could you tell me the difference beween:

$a = New-Object -Typename system.collections.arraylist

and

$a = [system.collections.arraylist]::new()

Is one of the above faster ? Does it work the same on PowerShell 7 with .net core or Windows PowerShell with .net Framework?

thx!

 

Jona

 

Short answer: Nothing. They both instantiate a new system.collections.arraylist object.

Details. The New-Object cmdlet “under the hood” calls a constructor method for the type specified plus the arguments provided (in this case none). New() is a default constructor method for system.collections.arraylist, so I suspect that is what New-Object is actually calling.

Ah so there is no speed difference?

For instance I read in an article that in the case of PSCustomobjects:

$Props = @{Name=‘jona’;Description=‘PowerShell’}

$a = new-object -typename psobject -property $Props (This one is slow and supported in Powv1 and up.

$a =[pscustomobject]$Props (This one works in Powv3 and up and supposed to be faster.

Is this the same for my initial question?

thx

Jona

 

I wasn’t considering speed difference in your question. The best way to determine that is to use Measure-Command. It will tell you definitively which is faster based on your data set.

Hi Mike,

Thank you I tried that and noticed no real difference.

 

thx

Jona

 

Based on my personal experience, it is the same thing, ::new is the original call and New-Object is simply a convenient and straight-forward command to instantiate it.

::new() wasn’t widely available until I think version 5. New-Object is the old school way that works back to version 1