Skip to content

Possible Set/Add-Content performance improvement #18070

Closed

Description

@iRon7

Summary of the new feature / enhancement

As appears from #8270 Suggestion: Add a chunking (partitioning, batching) mechanism to Select-Object, analogous to Get-Content -ReadCount the concerned cmdlets run faster when fed with batches. Presumable because the output file is (re)opened and closed for each individual item (or batch).
This suggested that a -WriteCount parameter as apposed to the -ReadCount parameter in Get-Content (which keeps the process/file open for a longer period) might improve the performance of the concerned cmdlets.

If the assumption¹ is correct that the output file is (re)opened and closed for each item in the pipeline, a simple "`-KeepOpen`" switch (or even a fixed change) where the file is closed at the end of the pipeline (output timeout) or the cmdlet is finalized might also a direction to improve the performance of these cmdlets.

1) I lack the C# knowledge to reverse engineer the concerned cmdlets and therefore can only base my assumptions on PowerShell knowledge and (performance) testing.

Name                           Value
----                           -----
PSVersion                      7.2.6
PSEdition                      Core
GitCommitId                    7.2.6
OS                             Microsoft Windows 10.0.22000
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Activity

  1. added
    Issue-Enhancement
    Needs-Triage
    on Sep 12, 2022
  2. jhoneill commented on Sep 12, 2022

    @jhoneill

    iRon7 that's not what your comment shows, I've answered it there, but your examples don't output the correct CSV.

    On my machine
    1..100000 |ForEach-Object { [pscustomobject]@{ id = $_; name = "name$_" } } |Export-Csv .\test2.csv
    takes about 20% longer than
    1..100000 |ForEach-Object { [pscustomobject]@{ id = $_; name = "name$_" } } | convertto-csv | out-null

    (the times are 1.2 vs 1.0 secs, ) and
    1..100000 |ForEach-Object { [pscustomobject]@{ id = $_; name = "name$_" } } | out-null
    takes 0.75 secs. So the file operations aren't much of the total.

    Looking at export-csv it doesn't open and close the file in the process block, it uses a stream-writer object and it flushes that as the last line of the process block. The end block calls code to flush and dispose of the stream-writer and the file-stream it uses. Possibly flushing the stream-writer less often would give a small perf boost (a few large writes should be faster than many small ones - I have a fast SSD in this machine, a slower disk would show bigger gains). So I wouldn't rule this out completely, but it may not be the huge improvement you thought.

  3. IISResetMe commented on Sep 12, 2022

    @IISResetMe
    Collaborator

    Presumable because the output file is (re)opened and closed for each individual item (or batch).

    This is not the case - Set-Content opens at most 2 file handles per pipeline invocation (1 for BOM detection, 1 for writing new content) - there's no closing/re-opening happening in between pipeline input being processed.

    The speedup comes (as James O'Neill (@jhoneill) explains above) from the fact that you only write 0.01% of the data you would have otherwise written to disk :)

  4. changed the title [-]Add `-WriteCount` to cmdlets as `Set/Add-Content` and `Export-Csv`[/-] [+]Add `-WriteCount` to cmdlets as `Set/Add-Content`[/+] on Sep 12, 2022
  5. iRon7 commented on Sep 12, 2022

    @iRon7
    Author

    James O'Neill (@jhoneill) , Mathias R. Jessen (@IISResetMe) ,

    Thanks for explaining that there's no closing/re-opening happening.

    My test with regards to the Export-Csv cmdlet were indeed incorrect (I removed it from the issue title) but I still see quiet a performance difference for the Set-Content cmdlet were the resulting output file is exactly the same:

    # This takes about 11 seconds:
    1..1000000 |Set-Content .\test1
    # This takes about 5 seconds (even there is an addition cmdlet in the chain):
    1..1000000 |Create-Batch -Size 10000 |Set-Content .\test2
    # (All in once) takes less than 0.5 seconds:
    (,@(1..1000000)) |Set-Content .\test3

    (Independent of the cause -that I might not understand-, it suggests that Set-Content could perform faster, or am I still missing something?)

  6. changed the title [-]Add `-WriteCount` to cmdlets as `Set/Add-Content`[/-] [+]Possible `Set/Add-Content` performance improvement[/+] on Sep 12, 2022
  7. jhoneill commented on Sep 12, 2022

    @jhoneill

    The fastest way is

    $x = 1..1000000  
    Set-Content .\test1 $x 
    

    You've show that something in the way Set-Content processes piped items can be optimized - but it would be very surprising if it went faster than avoiding the pipe completely and passing the items in a single step..

  8. iRon7 commented on Sep 12, 2022

    @iRon7
    Author

    but it would be very surprising if it went faster than avoiding the pipe completely

    I do not expect that but in case I do use the pipeline (e.g. to save memory), I actually do expect that it could be about twice as fast.

  9. SteveL-MSFT commented on Sep 12, 2022

    @SteveL-MSFT
    Member

    Anything that passes through the pipeline will be slower than than going through the pipeline. In this case, Set-Content file $x bypasses the pipeline completely whereas $x | Set-content file will pass each item, one-by-one, which is inherently slower. Or piping the array/collection at once vs each element: ,$x | Set-content file will be almost as pass as not using the pipeline at all.

  10. added
    Resolution-Answered
    and removed
    Needs-Triage
    on Sep 12, 2022
  11. iRon7 commented on Sep 13, 2022

    @iRon7
    Author

    @SteveL-MSFT,
    (Sorry, I have made a wrong and unclear start with this issue)

    Anything that passes through the pipeline will be slower than than going through the pipeline.

    That is what I would assume, but what about this:

    function Create-Batch {
        [CmdletBinding()]
        param (
            [ULong]$Size,
            [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]$InputObject
        )
        begin {
            $Batch = [Collections.Generic.List[object]]::new()
        }
        process {
            if ($Size -and $Batch.get_Count() -ge $Size) {
                ,$Batch
                $Batch = [Collections.Generic.List[object]]::new()
            }
            $Batch.Add($_)
        }
        End {
            if ($Batch.get_Count()) { ,$Batch }
        }
    }
    
    (Measure-Command {
        1..1000000 |Set-Content .\test1
    }).TotalSeconds
    6,8840292
    
    (Measure-Command {
        1..1000000 |Create-Batch -Size 10000 |Set-Content .\test2
    }).TotalSeconds
    2,5975531

    If I take the last part |Create-Batch -Size 10000 |Set-Content .\test2 and consider it as a single cmdlet, how can it be faster than just |Set-Content .\test1?

  12. jhoneill commented on Sep 13, 2022

    @jhoneill

    Anything that passes through the pipeline will be slower than than going through the pipeline. In this case, Set-Content file $x bypasses the pipeline completely whereas $x | Set-content file will pass each item, one-by-one, which is inherently slower.

    Steve Lee (@SteveL-MSFT) what is strange with this specific case is

    1. The time that $x | Set-content file takes scales linearly with the number of items in $x. So there isn't a $buffer = $buffer + $NewItem process copying more and more data as $x increases - because that takes order N-Squared time.
    2. $x | create-batch | Set-content file sends more down the pipeline - the same number of items get piped into Create-batch which does some work, and sends further items into set-content but the result is faster, despite the extra work happening to create and then unroll the array passed as a batch. So batching is cutting out something slow which runs once per item in Set-Content

    I still think the easy answer is if speed is an issue, and the total file size doesn't make memory a limitation, would be just to use
    $temp = Some command ; set-content -file file -value $temp

  13. iRon7 commented on Sep 14, 2022

    @iRon7
    Author

    Steve Lee (@SteveL-MSFT),
    Do we agree that the odd performance behavior shown here is not answered?
    If yes, can you remove the Resolution-Answered label to prevent it from automatically being closed?

  14. iRon7 commented on Sep 14, 2022

    @iRon7
    Author

    Note that the same behavior can be seen on the Out-File cmdlet:

    (Measure-Command {
         1..1000000 |Create-Batch -Size 10000 |Out-File .\OutFile2.txt
    }).TotalSeconds
    6,7076176

    vs.

    (Measure-Command {
        1..1000000 |Out-File .\OutFile1.txt
    }).TotalSeconds
    16,6025553

    I have not been able to exclude the file system (write cache?) any other cmdlets that I have tested so far are slower with batches.

  15. mklement0 commented on Sep 14, 2022

    @mklement0
    Contributor

    iRon7, in your example we're dealing with 1 million vs. 1,000 calls to Set-Content's ProcessRecord() method.

    While method calls always add overhead, I think what makes them particularly expensive in the case of Set-Content is the parameter-binding overhead: The pipeline-binding -Value parameter is object[]-typed, which means that for each scalar input object a one-element wrapper array is created.

    That is, 1 million 1-element arrays must be created on the fly in the non-batched call.
    In the batched call, 1000 List<object> instances must be converted to object[].

    Declaring the parameter as a scalar object, and letting the cmdlet's implementation determine whether a given input object is an array (enumerable) or not would improve performance.
    Given that non-batched input is the typical use case, this seems worth doing.

    The following benchmark code compares an object[]-typed (*_ArrayParam()) parameter with an object-typed one (*_ScalarParam), with respect to all-at-once, batched, and per-item (element) input.

    Note that it is optimized for object[] input, specifically; seemingly, enumerating an object found to implement IEnumerable via that interface in foreach is much slower than iterating over object[]

    Benchmark code
    Add-Type -ErrorAction Stop @'
    using System.Collections;
    public class Foo 
    {
      object[] all = new object[1000000];
      object[] chunks = new object[1000];
    
      public Foo()
      {
        for (int i = 0; i < 1000; ++i)
        {
          chunks[i] = new object[1000];
        }
      }
      public void PerItem_ArrayParam()
      {
        foreach (var el in all)
        {
          // Because -Value is object[]-typed, each scalar
          // is wrapped in an array on parameter binding.
          ProcessRecord_ArrayParam((new object[1] { el }));
        }
      }
    
      public void PerItem_ScalarParam()
      {
        foreach (var el in all)
        {
          ProcessRecord_ScalarParam(el);
        }
      }
    
      public void Batched_ArrayParam()
      {
        for (int i = 0; i < 1000; ++i)
        {
          ProcessRecord_ArrayParam((object[])chunks[i]);
        }
      }
    
      public void Batched_ScalarParam()
      {
        for (int i = 0; i < 1000; ++i)
        {
          ProcessRecord_ScalarParam(chunks[i]);
        }
      }
    
      public void AllAtOnce_ArrayParam()
      {
        ProcessRecord_ArrayParam(all);
      }
    
      public void AllAtOnce_ScalarParam()
      {
        ProcessRecord_ScalarParam(all);
      }
    
      // Array parameter, as Set-Content currently uses.
      public void ProcessRecord_ArrayParam(object[] arr)
      {
        foreach (var el in arr)
        {
          var dummy = el;
        }
      }
      
      // Scalar object parameter (which may receive arrays / collections)
      public void ProcessRecord_ScalarParam(object o)
      {
        if (o is object[] oarr) // Optimized for regular PS arrays. `Array` would be much slower, like `IEnumerable` below.
        {
          foreach (var el in oarr)
          {
            var dummy = el;
          }
        }
        else if (o is IEnumerable ienum) // !! This is considerably slower - in practice, more tests are needed to rule out hashtables, ...
        {
          foreach (var el in ienum)
          {
            var dummy = el;
          }
        }
        else  // scalar, use as-is.
        {       
           var dummy = o;
        }
      }
    }
    '@
    
    # Download and define function `Time-Command` on demand (will prompt).
    # To be safe, inspect the source code at the specified URL first.
    if (-not (Get-Command -ErrorAction Ignore Time-Command)) {
      $gistUrl = 'https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1'
      if ((Read-Host "`n====`n  OK to download and define benchmark function ``Time-Command```n  from Gist ${gistUrl}?`n=====`n(y/n)?").Trim() -notin 'y', 'yes') { Write-Warning 'Aborted.'; exit 2 }
      Invoke-RestMethod $gistUrl | Invoke-Expression 3>$null
      if (-not ${function:Time-Command}) { exit 2 }
    }
    
    $o = [Foo]::new()
    Time-Command @(
      { $o.PerItem_ArrayParam() }, 
      { $o.Batched_ArrayParam() }, 
      { $o.AllAtOnce_ArrayParam() }, 
      { $o.PerItem_ScalarParam() },
      { $o.Batched_ScalarParam() }, 
      { $o.AllAtOnce_ScalarParam() }
    )

    Sample results (M1 MacBook Pro, PowerShell Core 7.3.0-preview.7:

    Factor Secs (15-run avg.) Command                    TimeSpan
    ------ ------------------ -------                    --------
    1.00   0.001              $o.AllAtOnce_ArrayParam()  00:00:00.0012294
    1.01   0.001              $o.Batched_ArrayParam()    00:00:00.0012440
    1.02   0.001              $o.AllAtOnce_ScalarParam() 00:00:00.0012580
    1.06   0.001              $o.Batched_ScalarParam()   00:00:00.0012976
    4.10   0.005              $o.PerItem_ScalarParam()   00:00:00.0050410
    7.95   0.010              $o.PerItem_ArrayParam()    00:00:00.0097780
    

    As you can see, the performance of per-item processing improves roughly by a factor of 2, at least in this simple implementation - in practice, the determination of what what types should be enumerated presumably takes longer.

  16. jhoneill commented on Sep 14, 2022

    @jhoneill

    Just for fun

    PS>  (Measure-Command {
    >>     1..1000000 |Out-File .\OutFile1.txt
    >> }).TotalSeconds
    18.2000021
    
    PS>  (Measure-Command {
    >>     1..1000000 | out-string -Stream |Out-File .\OutFile1.txt
    >> }).TotalSeconds
    30.2555237
    
    PS>  (Measure-Command {
    >>     1..1000000 | out-string  |Out-File .\OutFile1.txt
    >> }).TotalSeconds
    11.9004971
    
    PS>  (Measure-Command {
    >>    $x = 1..1000000 ; out-string -InputObject $x  |Out-File .\OutFile1.txt
    >> }).TotalSeconds
    6.4771121
    
    

    1 is the "control"
    2 Shows out-string -stream gets slow with many items. (Strings appending?)
    3. Shows we can make Out-File go faster by sending Strings to it instead of numbers. No, I don't know why, but I'm guessing there's a not very efficient format operation.
    4. Shows not piping to to Out-String cuts the time more

  17. mklement0 commented on Sep 14, 2022

    @mklement0
    Contributor

    Note that Out-File and Out-String already have scalar -InputObject parameters, so they don't suffer from the same array-creation-per-scalar-input-object problem that Set-Content does.

    (As an aside: they have psobject parameters, not object; see discussion in #5551)

    Thus, perhaps the performance differences in your calls are primarily due to the count of ProcessRecord() calls involved:

    (1) has 1 million calls for Out-File
    (2) has 1 million calls for Out-String and 1 million for Out-File
    (3) has 1 million calls for Out-String, but only 1 for Out-File (because Out-String without -Stream emits a single string).
    (4) has 1 call for Out-String, and 1 for Out-File

  18. iRon7 commented on Sep 14, 2022

    @iRon7
    Author

    Michael Klement (@mklement0), James O'Neill (@jhoneill),

    Thanks for all the investigations.
    Btw, I am maintaining an updated Create-Batch cmdlet which e.g. now returns a Object[] (Rather than a Generic.List) batches. For this, I changed the output from ,$Batch to ,@($Batch) of virtually no additional costs which might indeed indicate something like a delayed execution that happens at the end-cmdlet which is either for each per-item or a whole batch.

  19. mklement0 commented on Sep 14, 2022

    @mklement0
    Contributor

    iRon7, returning object[] makes sense; a small caveat re @(): it is apparently optimized to recognize a List<object> operand and seemingly then merely calls its .ToArray() method, which is very fast.

    Generally, however, @() enumerates an expression value and builds an object[] array from the collected results, which is much slower. It would do that with List<int> for instance (element type other than object), and also does it with ArrayList (though it would seem that the same optimization as with List<object> could be applied).

    Thus, generally speaking, .ToArray(), if available on a list type, performs much better (though you won't necessarily get an object[] array).

  20. iRon7 commented on Sep 15, 2022

    @iRon7
    Author

    Michael Klement (@mklement0),

    While method calls always add overhead

    I guess that this actually means that the purpose #18071 ConvertTo-Csv and Export-Csv should unroll (embedded) arrays and lists will not result in an improved processing speed when supplied with all-at-once - or batched objects input but actually to a commonly lesser performance for usual per-item (element) inputs (and a similar performance as current cmdlet when supplied with all-at-once or batched of objects).

  21. mklement0 commented on Sep 15, 2022

    @mklement0
    Contributor

    iRon7, I originally neglected to consider that the overhead doesn't just come from method calls, but also from per-pipeline-input-object parameter binding (even when the avoidable overhead of array allocation for scalar inputs is not in the picture).

    Here's my current understanding:

    • Changing an existing cmdlet that does not perform its own enumeration to doing so will slow down streaming one-by-one processing, but, if done right, only marginally. This comes from having to perform reflection on each input object to determine if it is an enumerable or not.

    • If done right, making a cmdlet perform its own enumeration does result in significant performance gains with all-at-once input or (large) batches.

    Here's a proof-of-concept, based on defining two simple binary cmdlets, Add-OneSimple and Add-OneEnumerate, the former not doing its own enumeration, the latter doing so.
    They accept object input, to which, if an object is found to be an int, 1 is added on output.
    In Add-OneEnumerate, LanguagePrimitives.GetEnumerator() is used to conditionally return an enumerator, if an object is found to be enumerable.

    Code
    Add-Type @'
        using System;
        using System.Management.Automation;
        using System.Collections;
    
        [Cmdlet("Add", "OneSimple")]
        public class AddOneCommandSimple : PSCmdlet {
    
            [Parameter(ValueFromPipeline=true, Position=0)]
            public object InputObject { get; set; }
    
            // Some dummy parameters
            [Parameter()]
            public string Dummy1 { get; set; }
            [Parameter()]
            public int Dummy2 { get; set; }
            [Parameter()]
            public long Dummy3 { get; set; }
            [Parameter()]
            public string Dummy4 { get; set; }
    
            protected override void ProcessRecord() {
                object o = InputObject is PSObject pso ? pso.BaseObject : InputObject;
                if (o is int i)
                {
                    WriteObject(i + 1);
                }
                else
                {
                    WriteObject($@"not an int: {o}, {o.GetType().Name}");
                }
            }
        }
    
        [Cmdlet("Add", "OneEnumerate")]
        public class AddOneCommandEnumerate : PSCmdlet {
    
            [Parameter(ValueFromPipeline=true, Position=0)]
            public object InputObject { get; set; }
    
            // Some dummy parameters
            [Parameter()]
            public string Dummy1 { get; set; }
            [Parameter()]
            public int Dummy2 { get; set; }
            [Parameter()]
            public long Dummy3 { get; set; }
            [Parameter()]
            public string Dummy4 { get; set; }
    
            protected override void ProcessRecord() {
                IEnumerator enumerator = LanguagePrimitives.GetEnumerator(InputObject);
                if (enumerator is not null)
                {
                    while (enumerator.MoveNext())
                    {
                        Impl(enumerator.Current);
                    }
                }
                else {
                    Impl(InputObject);
                }
            }
    
            private void Impl(object o) {
                if (o is PSObject pso)
                {
                    o = pso.BaseObject;
                }
                if (o is int i)
                {
                    WriteObject(i + 1);
                }
                else
                {
                    WriteObject($@"not an int: {o}, {o.GetType().Name}");
                }
            }
        }
    
    '@ -PassThru | ForEach-Object Assembly | Import-Module
    
    # Download and define function `Time-Command` on demand (will prompt).
    # To be safe, inspect the source code at the specified URL first.
    if (-not (Get-Command -ErrorAction Ignore Time-Command)) {
        $gistUrl = 'https://gist.github.com/mklement0/9e1f13978620b09ab2d15da5535d1b27/raw/Time-Command.ps1'
        if ((Read-Host "`n====`n  OK to download and define benchmark function ``Time-Command```n  from Gist ${gistUrl}?`n=====`n(y/n)?").Trim() -notin 'y', 'yes') { Write-Warning 'Aborted.'; exit 2 }
        Invoke-RestMethod $gistUrl | Invoke-Expression 3>$null
        if (-not ${function:Time-Command}) { exit 2 }
      }
    
    # Sample input array ([object[]])
    $a = 1..1e5
    
    Time-Command @(
      { $null = $a | Add-OneSimple },
      { $null = $a | Add-OneEnumerate },
      { $null = , $a | Add-OneEnumerate },
      { $null = Add-OneEnumerate -InputObject $a }
    )
    

    Sample timings with 100,000 input objects, from my M1 MacBook Pro running PowerShell Core 7.3.0-preview.7:

    Factor Secs (15-run avg.) Command                                  TimeSpan
    ------ ------------------ -------                                  --------
    1.00   0.033              $null = , $a | Add-OneEnumerate          00:00:00.0326625
    1.01   0.033              $null = Add-OneEnumerate -InputObject $a 00:00:00.0329941
    7.46   0.244              $null = $a | Add-OneSimple               00:00:00.2437299
    7.64   0.250              $null = $a | Add-OneEnumerate            00:00:00.2496487
    

    As you can see:

    • the all-input-at-once calls significantly outperform the one-by-one calls
    • in the one-by-one calls, the enumerating cmdlet is only marginally slower than the non-enumerating one
  22. iRon7 commented on Sep 17, 2022

    @iRon7
    Author

    Michael Klement (@mklement0), thanks again for the further investigations and clarifications

    ... but, if done right, only marginally ...

    Bottom line, I understand that this all means:

    1. that besides that there wouldn't virtually any performance disadvantage of implementing an all-at-once/"batch" input for cmdlets along with ConvertTo-Csv/ExportTo-Csv (ConvertTo-Csv and Export-Csv should unroll (embedded) arrays and lists #18071),
    2. the cmdlets Set-Content/Add-Content and Out-File (and all other cmdlets that support an all-at-once/"batch" input including the default display output/Write-Output) might actually not do the right thing here?
  23. mklement0 commented on Sep 17, 2022

    @mklement0
    Contributor

    Re 1: Yes, I think that ConvertTo-Csv and Export-Csv - along with all the other ones in Category C (from #4242) - could be "batch-enhanced" without negatively impacting one-by-one processing (in a meaningful way).

    Re 2: Among the Category B cmdlets - which are "batch-enhanced" already - Set-Content / Add-Content and Join-Content could be improved to benefit the one-by-one case, by defining their -Value / -InputObject as object rather than object[], which the others in that category, including Out-File, already do.

  24. ghost closed this as completedon Sep 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-EnhancementResolution-Answered

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions