Monthly Archive

Categories

Creating collections for output

There are many times when you end up creating a collection – either for output or use for performing further processing. There’s a common pattern that’s used when creating collections for output that’s very inefficient.

 

That pattern is:

$data = @()
97..122 | foreach {
$props = @{
Number = $_
Letter = [char][byte]$_
}

$data += New-Object -TypeName PSobject -Property $props

}

$data

Create an empty array. Build a pipeline to get the data you want and for each object on that pipeline create an output object and add it to the array. Output the array.

This is inefficient because each time you think you’re adding an object to the array you’re really creating a new array from the current contents of the array and the new object.

I used to use this approach a lot and it wasn’t until I sat and thought about it while working on PowerShell in Action that I realised what I was doing wrong.

 

A more efficient approach is to let PowerShell automatically create the collection for you.

$data = 97..122 | foreach {
$props = @{
Number = $_
Letter = [char][byte]$_
}

New-Object -TypeName PSobject -Property $props

}

$data

 

Just output your results at the end of the pipeline and PowerShell will create the array for you.

It also works with a foreach loop

$data = foreach ($num in 97..122 ) {
$props = @{
Number = $num
Letter = [char][byte]$num
}

New-Object -TypeName PSobject -Property $props

}

$data

Comments are closed.