Skip to content

Commit c9e5201

Browse files
committed
Add perf comparisons for creating new objects
1 parent 49093a4 commit c9e5201

File tree

1 file changed

+62
-1
lines changed

1 file changed

+62
-1
lines changed

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

Lines changed: 62 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: 05/07/2024
3+
ms.date: 12/05/2024
44
title: PowerShell scripting performance considerations
55
---
66

@@ -627,6 +627,67 @@ Unwrapped = 42.92 ms
627627
The unwrapped example is **372 times faster**. Also, notice that the first implementation requires
628628
the **Append** parameter, which isn't required for the later implementation.
629629

630+
## Object creation
631+
632+
Creating objects using the `New-Object` cmdlet can be slow. The following code compares the
633+
performance of creating objects using the `New-Object` cmdlet to the `[pscustomobject]` type
634+
accelerator.
635+
636+
```powershell
637+
Measure-Command {
638+
$test = 'PSCustomObject'
639+
for ($i = 0; $i -lt 100000; $i++) {
640+
$resultObject = [PSCustomObject]@{
641+
Name = 'Name'
642+
Path = 'FullName'
643+
}
644+
}
645+
} | Select-Object @{n='Test';e={$test}},TotalSeconds
646+
647+
Measure-Command {
648+
$test = 'New-Object'
649+
for ($i = 0; $i -lt 100000; $i++) {
650+
$resultObject = New-Object -TypeName PSObject -Property @{
651+
Name = 'Name'
652+
Path = 'FullName'
653+
}
654+
}
655+
} | Select-Object @{n='Test';e={$test}},TotalSeconds
656+
```
657+
658+
```Output
659+
Test TotalSeconds
660+
---- ------------
661+
PSCustomObject 0.48
662+
New-Object 3.37
663+
```
664+
665+
PowerShell 5.0 added the `new()` static method for all .NET types. The following code compares the
666+
performance of creating objects using the `New-Object` cmdlet to the `new()` method.
667+
668+
```powershell
669+
Measure-Command {
670+
$test = 'new() method'
671+
for ($i = 0; $i -lt 100000; $i++) {
672+
$sb = [System.Text.StringBuilder]::new(1000)
673+
}
674+
} | Select-Object @{n='Test';e={$test}},TotalSeconds
675+
676+
Measure-Command {
677+
$test = 'New-Object'
678+
for ($i = 0; $i -lt 100000; $i++) {
679+
$sb = New-Object -TypeName System.Text.StringBuilder -ArgumentList 1000
680+
}
681+
} | Select-Object @{n='Test';e={$test}},TotalSeconds
682+
```
683+
684+
```Output
685+
Test TotalSeconds
686+
---- ------------
687+
new() method 0.59
688+
New-Object 3.17
689+
```
690+
630691
## Use OrderedDictionary to dynamically create new objects
631692

632693
There are situations where we may need to dynamically create objects based on some input, the

0 commit comments

Comments
 (0)