Skip to content

Instantly share code, notes, and snippets.

@rodmhgl
Created June 8, 2018 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodmhgl/54925b064d451f6b7ae02a6c8266a67c to your computer and use it in GitHub Desktop.
Save rodmhgl/54925b064d451f6b7ae02a6c8266a67c to your computer and use it in GitHub Desktop.
Demonstrates assigning object collection with Array addition versus Direct Assignment
$blah = get-childitem -Path c:\temp -Directory
$AddedTicks = Measure-Command -Expression {
$AddedToArray = @()
foreach ($b in $blah) {
$myOBJ = New-Object System.Object
$myOBJ | Add-Member -Type NoteProperty -Name IsBlah -Value $b.BaseName
$AddedToArray += $myOBJ
}
} | Select-Object Ticks
# Cleanup
Remove-Variable colArray -Force -ErrorAction SilentlyContinue
$AssignedTicks = Measure-Command -Expression {
$AssignedWithForEach = foreach ($b in $blah) {
$myOBJ = New-Object System.Object
$myOBJ | Add-Member -Type NoteProperty -Name IsBlah -Value $b.BaseName
$myOBJ
}
} | Select-Object Ticks
"Adding to array executed in $($AddedTicks.Ticks) ticks and produced a $($AddedToArray.GetType()) with $($AddedToArray.count) elements."
"Assigning via ForEach executed in $($AssignedTicks.Ticks) ticks and produced a $($AssignedWithForEach.GetType()) with $($AssignedWithForEach.count) elements."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment