|
1 | 1 | --- |
2 | 2 | description: Scripting for Performance in PowerShell |
3 | | -ms.date: 05/07/2024 |
| 3 | +ms.date: 12/05/2024 |
4 | 4 | title: PowerShell scripting performance considerations |
5 | 5 | --- |
6 | 6 |
|
@@ -627,6 +627,67 @@ Unwrapped = 42.92 ms |
627 | 627 | The unwrapped example is **372 times faster**. Also, notice that the first implementation requires |
628 | 628 | the **Append** parameter, which isn't required for the later implementation. |
629 | 629 |
|
| 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 | + |
630 | 691 | ## Use OrderedDictionary to dynamically create new objects |
631 | 692 |
|
632 | 693 | There are situations where we may need to dynamically create objects based on some input, the |
|
0 commit comments