Skip to content

Commit

Permalink
Merge pull request #24 from santisq/main
Browse files Browse the repository at this point in the history
Adding Performance tip for Array Addition
  • Loading branch information
deadlydog authored Sep 22, 2023
2 parents c22a7e6 + 0d8f164 commit 73f0f81
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/PowerShellTips/2023-09-22-avoid-array-addition.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
$tip = [tiPS.PowerShellTip]::new()
$tip.CreatedDate = [DateTime]::Parse('2023-09-22')
$tip.Title = 'Avoid Array addition'
$tip.TipText = @'
Array addition is a expensive and inefficient operation and can, most of the times, be replaced by PowerShell explicit loop assignment.
Use a `List<T>` instead in those cases when adding to a collection while looping is required.
'@
$tip.Example = @'
# Array addition:
$result = @()
foreach ($i in 0..10) {
$result += $i
}
# Can be easily replaced with explicit assignemnt:
$result = foreach ($i in 0..10) {
$i
}
# And, when not possible, a List<T> is recommended:
$result = [System.Collections.Generic.List[int]]::new()
foreach ($i in 0..10) {
$result.Add($i)
}
'@
$tip.Urls = @(
'https://learn.microsoft.com/en-us/powershell/scripting/dev-cross-plat/performance/script-authoring-considerations?view=powershell-7.3#array-addition'
)
$tip.MinPowerShellVersion = '5.1'
$tip.Category = [tiPS.TipCategory]::Other # Community, CoreCmdlet, Editor, Module, Syntax, Terminal, or Other.

0 comments on commit 73f0f81

Please sign in to comment.