Skip to content

Commit fb4fea7

Browse files
authored
Add example for type-safe lists (#12687)
1 parent 2ec30d3 commit fb4fea7

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

reference/docs-conceptual/dev-cross-plat/performance/script-authoring-considerations.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
description: Scripting for Performance in PowerShell
3-
ms.date: 08/18/2025
3+
ms.date: 01/21/2026
44
title: PowerShell scripting performance considerations
55
---
66

@@ -267,6 +267,42 @@ In this example, PowerShell creates an `[ArrayList]` to hold the results written
267267
inside the array expression. Just before assigning to `$results`, PowerShell converts the
268268
`[ArrayList]` to an `[Object[]]`.
269269

270+
### Type-safe collections
271+
272+
PowerShell is a loosely typed language, which makes coding easier but can have performance
273+
implications. Consider using type-safe (or type-specific) collections. Type-safe collections consume
274+
less memory and are faster. Compare the following examples:
275+
276+
```powershell
277+
$Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
278+
$ListInt = [System.Collections.Generic.List[int]]::new()
279+
for ($i = 0; $i -lt 1mb; $i++) {
280+
$ListInt.Add($i)
281+
}
282+
$Stopwatch.Stop()
283+
Write-Host "Time to add 1mb integers to List[int]: $($Stopwatch.Elapsed.TotalSeconds) seconds."
284+
```
285+
286+
```Output
287+
Time to add 1mb integers to List[int]: 9.8841501 seconds.
288+
```
289+
290+
Creating a list of `[int]` is faster than creating a list of `[Object]`.
291+
292+
```powershell
293+
$Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
294+
$ListObject = [System.Collections.Generic.List[Object]]::new()
295+
for ($i = 0; $i -lt 1mb; $i++) {
296+
$ListObject.Add($i)
297+
}
298+
$Stopwatch.Stop()
299+
Write-Host "Time to add 1mb integers to List[Object]: $($Stopwatch.Elapsed.TotalSeconds) seconds."
300+
```
301+
302+
```Output
303+
Time to add 1mb integers to List[Object]: 10.5677782 seconds.
304+
```
305+
270306
## String addition
271307

272308
Strings are immutable. Each addition to the string actually creates a new string big enough to hold

0 commit comments

Comments
 (0)