-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy path2023-09-22-avoid-array-addition.ps1
More file actions
31 lines (28 loc) · 1.04 KB
/
2023-09-22-avoid-array-addition.ps1
File metadata and controls
31 lines (28 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$tip = [tiPS.PowerShellTip]::new()
$tip.CreatedDate = [DateTime]::Parse('2023-09-22')
$tip.Title = 'Avoid Array addition'
$tip.TipText = @'
Array addition is an expensive and inefficient operation and can usually 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:
$items = @()
foreach ($i in 0..10) {
$items += $i
}
# Can be easily replaced with explicit assignment:
$items = foreach ($i in 0..10) {
$i
}
# And, when not possible, a List<T> is recommended:
$items = [System.Collections.Generic.List[int]]::new()
foreach ($i in 0..10) {
$items.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.Category = [tiPS.TipCategory]::Performance # Community, Editor, Module, NativeCmdlet, Performance, Security, Syntax, Terminal, or Other.
$tip.Author = 'Santiago Squarzon (santisq)'