Repository navigation
Description
Summary of the new feature / enhancement
I was looking into += as the canonical example of inefficient powershell code for my presentation at psconfeu, and noticed that doing += on 10k items allocates 1.5 GB of memory and forces many garbage collections. This is way more allocations than the common wisdom of "it copies array once for every item" suggests.
$start = [GC]::GetTotalAllocatedBytes($true)
$numbers = 1..10000
$newNumbers = @()
foreach ($number in $numbers) {
$newNumbers += $number
}
$end = [GC]::GetTotalAllocatedBytes($true)
"$([System.Math]::Round(($end-$start) / 1GB, 2)) GB"The relevant code in powershell:
This code handles the array as enumerable of unknown size, instead of special casing it to avoid growing the list over and over as it resizes from the initial capacity of 4 items. So for example for the final items in my 10k array it grows the list 12 times per item.
This can be confirmed by profiling the code in VS allocation profiler, where many of the allocations are attributed to arrays that have sizes which are multiplies of 2.
Proposed technical implementation details (optional)
as suggested by Patrick Meinecke (@SeeminglyScience)
a simple optimization could be just adding a sizeHint param to AddObject
Or
the binder, to emit different code gen based on the type

Activity
StartAutomating commentedon Jun 7, 2024
Jakub Jareš (@nohwnd) Patrick Meinecke (@SeeminglyScience) please do this!
rhubarb-geek-nz commentedon Jun 7, 2024
I suggest that syntax like += is for convenience, not performance. For example is it well-known that it is better to use StringBuilder that appending individual strings.
If you already know you are likely to be in a situation where performance matters then using New-Object System.Collection.ArrayList and Add yourself allows you to be in control and should address the issue.
jborean93 commentedon Jun 7, 2024
I've opened #23901 which can take advantage of
Array.Resizewhen the LHS of+=is ofobject[]type. While I agree that+=is poor form I think trying to make the very common usage of this more efficient where we can a laudable goal.SeeminglyScience commentedon Jun 7, 2024
Sure, but in our case the implementation for
+=for arrays is arbitrarily exponentially worse than it needs to be.While I do tend to use
StringBuilder, it turns out the benefit over+=isn't all that profound for most cases.fyi you'd really want to avoid
New-Objectfor perf. Not a big hit for a single time before looping, but still worth mentioning since we're talking about perf. Though really a simple assignment is better anyway (e.g.$all = foreach ($a in $b) { stuff })StartAutomating commentedon Jun 7, 2024
Patrick Meinecke (@SeeminglyScience) is 💯 right here.
+= being slow is a performance tax everyone pays without realizing it.
Fixing this without fundamentally breaking existing scripts would be pretty big.
It would remove an area of nearly constant complaint about PowerShell since the beginning.
SeeminglyScience commentedon Jun 7, 2024
Just to clarify, it'll still be slower, potentially a lot slower. The thing we've always told folks about why it's slow will still be true. That slow just won't be arbitrarily many times worse.
But it's possible that slow will only be noticeable at much larger scales than previous, which is still very nice
rhubarb-geek-nz commentedon Jun 7, 2024
Regarding performance, the downside of using $myArray.Add($obj) is that every single invocation of Add gets serialised and passed to AMSI, just like $myStringBuilder.Append($str)
iRon7 commentedon Jun 7, 2024
I don't want to wave away that there is probably room to improve the increase assignment operator (
+=) behavior but like to note that .net programming experts (e.g. C# engineers) tend to neglect and underestimate the PowerShell Pipeline and miss the beauty of the already existing idiomatic PowerShell syntax for building a collection:0 GBThe performance might be a little less than using an
Addmethod but there is no garbage left.Related:
237dmitry commentedon Jun 7, 2024
Question: Could
[GC]::GetTotalAllocatedBytes($true)be using for native commands to determine their statistic?nohwnd commentedon Jun 7, 2024
That depends on what you mean by native. If by native, you mean an executable like notepad.exe, then no because it cannot see across the process boundary.
If by native, you mean functions or commandments that run in partial, then yes, and that is what the Profiler module does:
https://github.com/nohwnd/Profiler
Even though the profiler does not use the accurate mode ($true above) by default because it traces every single point in the script.
237dmitry commentedon Jun 7, 2024
By native I mean applications that do not depend on pwsh. For example I run previous script:
SeeminglyScience commentedon Jun 7, 2024
GC.GetTotalAllocatedByteswill look at managed heap allocations. It won't show out of process allocations nor will it reflect memory allocated viaglibc!*allocorkernel32!LocalAlloc. Only memory managed by the CLRmklement0 commentedon Jun 7, 2024
👍 for making
+=more efficient.Unfortunately, the discussion around introducing syntactic sugar for efficiently extensible list-like types along with concomitant efficient use of
+=has stalled - see #5643SeeminglyScience commentedon Jun 11, 2024
It'll probably end up being a little faster actually since the engine is the thing doing the logic of adding to a list. Marginal difference either way, and I totally agree that it's still what I would recommend even if
+=becomes comparable.0..10000just isn't enough to reach GBs. It allocates around 4mb in total. That's still significantly more than I would have expected as 10k boxed ints in an array should be around 120kb. Expected to be a few times higher than that to account for the list, pipe allocation, and at least two arrays. But 4mb still seems high. Probably something else to look into there.nohwnd commentedon Jun 12, 2024
When I measure 1...10000 I see 0.31 MB, not 4 MB, which seems reasonably close to the actual array.
SeeminglyScience commentedon Jun 12, 2024
Sorry for not being clear, I meant 4mb from the example they were using:
microsoft-github-policy-service commentedon Jun 17, 2024
📣 Hey Jakub Jareš (@nohwnd), how did we do? We would love to hear your feedback with the link below! 🗣️
🔗 https://aka.ms/PSRepoFeedback