You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Possible Set/Add-Content performance improvement #18070
As appears from #8270Suggestion: 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.6PSEdition CoreGitCommitId 7.2.6OS Microsoft Windows 10.0.22000Platform Win32NTPSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}PSRemotingProtocolVersion 2.3SerializationVersion 1.1.0.1WSManStackVersion 3.0
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.
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 :)
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
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?)
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..
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.
functionCreate-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?
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.
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.
$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
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?
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 scalarobject, 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 IEnumerablevia 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.'; exit2 }
Invoke-RestMethod$gistUrl|Invoke-Expression3>$nullif (-not${function:Time-Command}) { exit2 }
}
$o= [Foo]::new()
Time-Command @(
{ $o.PerItem_ArrayParam() },
{ $o.Batched_ArrayParam() },
{ $o.AllAtOnce_ArrayParam() },
{ $o.PerItem_ScalarParam() },
{ $o.Batched_ScalarParam() },
{ $o.AllAtOnce_ScalarParam() }
)
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.
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
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
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.
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).
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).
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:
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?
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.
Activity
jhoneill commentedon Sep 12, 2022
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.csvtakes 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-nulltakes 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
processblock, it uses a stream-writer object and it flushes that as the last line of the process block. Theendblock 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.IISResetMe commentedon Sep 12, 2022
This is not the case -
Set-Contentopens 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 :)
[-]Add `-WriteCount` to cmdlets as `Set/Add-Content` and `Export-Csv`[/-][+]Add `-WriteCount` to cmdlets as `Set/Add-Content`[/+]iRon7 commentedon Sep 12, 2022
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-Csvcmdlet were indeed incorrect (I removed it from the issue title) but I still see quiet a performance difference for theSet-Contentcmdlet were the resulting output file is exactly the same:(Independent of the cause -that I might not understand-, it suggests that
Set-Contentcould perform faster, or am I still missing something?)[-]Add `-WriteCount` to cmdlets as `Set/Add-Content`[/-][+]Possible `Set/Add-Content` performance improvement[/+]jhoneill commentedon Sep 12, 2022
The fastest way is
You've show that something in the way
Set-Contentprocesses 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..iRon7 commentedon Sep 12, 2022
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.
SteveL-MSFT commentedon Sep 12, 2022
Anything that passes through the pipeline will be slower than than going through the pipeline. In this case,
Set-Content file $xbypasses the pipeline completely whereas$x | Set-content filewill pass each item, one-by-one, which is inherently slower. Or piping the array/collection at once vs each element:,$x | Set-content filewill be almost as pass as not using the pipeline at all.iRon7 commentedon Sep 13, 2022
@SteveL-MSFT,
(Sorry, I have made a wrong and unclear start with this issue)
That is what I would assume, but what about this:
If I take the last part
|Create-Batch -Size 10000 |Set-Content .\test2and consider it as a single cmdlet, how can it be faster than just|Set-Content .\test1?jhoneill commentedon Sep 13, 2022
Steve Lee (@SteveL-MSFT) what is strange with this specific case is
$x | Set-content filetakes scales linearly with the number of items in $x. So there isn't a$buffer = $buffer + $NewItemprocess copying more and more data as $x increases - because that takes order N-Squared time.$x | create-batch | Set-content filesends more down the pipeline - the same number of items get piped intoCreate-batchwhich does some work, and sends further items intoset-contentbut 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 inSet-ContentI 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 $tempiRon7 commentedon Sep 14, 2022
Steve Lee (@SteveL-MSFT),
Do we agree that the odd performance behavior shown here is not answered?
If yes, can you remove the
Resolution-Answeredlabel to prevent it from automatically being closed?iRon7 commentedon Sep 14, 2022
Note that the same behavior can be seen on the
Out-Filecmdlet:vs.
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.
mklement0 commentedon Sep 14, 2022
iRon7, in your example we're dealing with 1 million vs. 1,000 calls to
Set-Content'sProcessRecord()method.While method calls always add overhead, I think what makes them particularly expensive in the case of
Set-Contentis the parameter-binding overhead: The pipeline-binding-Valueparameter isobject[]-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 toobject[].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 anobject-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 anobjectfound to implementIEnumerablevia that interface inforeachis much slower than iterating overobject[]Benchmark code
Sample results (M1 MacBook Pro, PowerShell Core 7.3.0-preview.7:
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.
jhoneill commentedon Sep 14, 2022
Just for fun
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
mklement0 commentedon Sep 14, 2022
Note that
Out-FileandOut-Stringalready have scalar-InputObjectparameters, so they don't suffer from the same array-creation-per-scalar-input-object problem thatSet-Contentdoes.(As an aside: they have
psobjectparameters, notobject; 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-Stringand 1 million forOut-File(3) has 1 million calls for
Out-String, but only 1 forOut-File(becauseOut-Stringwithout-Streamemits a single string).(4) has 1 call for
Out-String, and 1 forOut-FileiRon7 commentedon Sep 14, 2022
Michael Klement (@mklement0), James O'Neill (@jhoneill),
Thanks for all the investigations.
Btw, I am maintaining an updated
Create-Batchcmdlet which e.g. now returns aObject[](Rather than aGeneric.List) batches. For this, I changed the output from,$Batchto,@($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.mklement0 commentedon Sep 14, 2022
iRon7, returning
object[]makes sense; a small caveat re@(): it is apparently optimized to recognize aList<object>operand and seemingly then merely calls its.ToArray()method, which is very fast.Generally, however,
@()enumerates an expression value and builds anobject[]array from the collected results, which is much slower. It would do that withList<int>for instance (element type other thanobject), and also does it withArrayList(though it would seem that the same optimization as withList<object>could be applied).Thus, generally speaking,
.ToArray(), if available on a list type, performs much better (though you won't necessarily get anobject[]array).iRon7 commentedon Sep 15, 2022
Michael Klement (@mklement0),
I guess that this actually means that the purpose #18071
ConvertTo-CsvandExport-Csvshould 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).mklement0 commentedon Sep 15, 2022
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-OneSimpleandAdd-OneEnumerate, the former not doing its own enumeration, the latter doing so.They accept
objectinput, to which, if an object is found to be anint,1is added on output.In
Add-OneEnumerate,LanguagePrimitives.GetEnumerator()is used to conditionally return an enumerator, if an object is found to be enumerable.Code
Sample timings with
100,000input objects, from my M1 MacBook Pro running PowerShell Core 7.3.0-preview.7:As you can see:
iRon7 commentedon Sep 17, 2022
Michael Klement (@mklement0), thanks again for the further investigations and clarifications
Bottom line, I understand that this all means:
ConvertTo-Csv/ExportTo-Csv(ConvertTo-CsvandExport-Csvshould unroll (embedded) arrays and lists #18071),Set-Content/Add-ContentandOut-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?mklement0 commentedon Sep 17, 2022
Re 1: Yes, I think that
ConvertTo-CsvandExport-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-ContentandJoin-Contentcould be improved to benefit the one-by-one case, by defining their-Value/-InputObjectasobjectrather thanobject[], which the others in that category, includingOut-File, already do.