Difference new-object and ::new()

Welcome Forums General PowerShell Q&A Difference new-object and ::new()

Viewing 4 reply threads
  • Author
    Posts
    • #269975
      Participant
      Topics: 3
      Replies: 5
      Points: 37
      Rank: Member

      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

       

    • #269999
      Participant
      Topics: 5
      Replies: 177
      Points: 686
      Helping Hand
      Rank: Major Contributor

      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.

    • #270364
      Participant
      Topics: 3
      Replies: 5
      Points: 37
      Rank: Member

      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

       

    • #270376
      Participant
      Topics: 5
      Replies: 177
      Points: 686
      Helping Hand
      Rank: Major Contributor

      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.

    • #270544
      Participant
      Topics: 3
      Replies: 5
      Points: 37
      Rank: Member

      Hi Mike,

      Thank you I tried that and noticed no real difference.

       

      thx

      Jona

       

Viewing 4 reply threads
  • You must be logged in to reply to this topic.