Repository navigation
Improve Array BinaryAdd Method for object[] - #23901
Conversation
Use Array.Resize when doing += on an array type. This is more efficient than the default BinaryAdd done on other enumerable types. As adding to an array is a common operation done by people new to PowerShell this should reduce some of the issues which come with that type of code.
In scripts/functions yes, but if this really reduces time spent on += by 90% I'll likely never bother using lists in interactive sessions anymore. Wow 🙌 |
|
The Engine WG discussed this and agree with the change, and it is ready to be reviewed. |
Ilya (iSazonov)
left a comment
There was a problem hiding this comment.
nit: interesting, have we such issues with Collection, List (and others IEnumarable-s?
Somewhat yes, at least the known size types (not |
I would lean toward "maybe, but out of scope for this PR" just to get the most common use case settled quickly. |
To be fair, interactively it's really hard to beat statement capture (e.g. |
True. I'm usually a few foreach-loops deep or splitting into multiple arrays when I need Either way, looking forward to this. |
|
This is a great improvement to PowerShell 🎉. Btw. a similar issue exists for using the increase assignment operator (
|
|
This is an extended test from https://learn.microsoft.com/en-us/powershell/scripting/whats-new/what-s-new-in-powershell-75?view=powershell-7.5#performance-improvements A $tests = @{
'Direct Assignment' = {
param($count)
$result = foreach($i in 1..$count) {
$i
}
}
'List<T>.Add(T)' = {
param($count)
$result = [Collections.Generic.List[int]]::new()
foreach($i in 1..$count) {
$result.Add($i)
}
}
'Array+= Operator' = {
param($count)
$result = @()
foreach($i in 1..$count) {
$result += $i
}
}
'Hashtable' = {
param($count)
$result = [ordered]@{}
#$result = @{}
foreach($i in 1..$count) {
$result["i$i"] = $i
}
}
} # tests
1kb, 5kb, 10kb | ForEach-Object {
$groupResult = foreach($test in $tests.GetEnumerator()) {
$ms = (Measure-Command { & $test.Value -Count $_ }).TotalMilliseconds
[pscustomobject]@{
CollectionSize = $_
Test = $test.Key
TotalMilliseconds = [Math]::Round($ms, 2)
}
[GC]::Collect()
[GC]::WaitForPendingFinalizers()
}
$groupResult = $groupResult | Sort-Object TotalMilliseconds
$groupResult | Select-Object *, @{
Name = 'RelativeSpeed'
Expression = {
$relativeSpeed = $_.TotalMilliseconds / $groupResult[0].TotalMilliseconds
$speed = [Math]::Round($relativeSpeed, 2).ToString() + 'x'
if ($speed -eq '1x') { $speed } else { $speed + ' slower' }
}
} | Format-Table -AutoSize
}Output: CollectionSize Test TotalMilliseconds RelativeSpeed
-------------- ---- ----------------- -------------
1024 Direct Assignment 1,31 1x
1024 Hashtable 1,49 1,14x slower
1024 Array+= Operator 3,60 2,75x slower
1024 List<T>.Add(T) 10,78 8,23x slower
CollectionSize Test TotalMilliseconds RelativeSpeed
-------------- ---- ----------------- -------------
5120 Direct Assignment 0,32 1x
5120 Hashtable 1,50 4,69x slower
5120 Array+= Operator 16,93 52,91x slower
5120 List<T>.Add(T) 49,56 154,88x slower
CollectionSize Test TotalMilliseconds RelativeSpeed
-------------- ---- ----------------- -------------
10240 Direct Assignment 0,46 1x
10240 Hashtable 2,94 6,39x slower
10240 Array+= Operator 69,77 151,67x slower
10240 List<T>.Add(T) 96,96 210,78x slowerMy Environment: PS#> $psversiontable
Name Value
---- -----
PSVersion 7.5.4
PSEdition Core
GitCommitId 7.5.4
OS Microsoft Windows 10.0.26200
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
|
This comment was marked as off-topic.
This comment was marked as off-topic.
collection performance
duplication is not the case, just add a unique value for a key |
|
I would suggest opening a discussion if you have suggestions for additional areas of improvement, comments on a long merged PR are unlikely to amount to anything. That said, this PR was a special case where the previous implementation was so egregiously slow and the usage of the pattern is so high that the value-add was undeniable. It's generally safe to assume every single area of the engine could use performance tweaks, given unlimited dev time. |
|
I apologize for any unnecessary "noise" and misunderstanding. Perhaps the best place would be the
|
PR Summary
Use Array.Resize when doing += on an array type. This is more efficient than the default BinaryAdd done on other enumerable types. As adding to an array is a common operation done by people new to PowerShell this should reduce some of the issues which come with that type of code.
An example of dramatic difference this can make is reflected by this code
When run with the new code (
TEST=true) you can see it is 8 seconds faster and requires less memory to allocate. As the arrays get larger the differences are even more profound.This doesn't negate the existing performance impacts of adding to an array, it just removes extra work that wasn't needed in the first place (which was pretty inefficient) making it slower than it has to. People should still use an alternative like capturing the output from the pipeline or use
List<T>.PR Context
Partially Fixes: #23899
PR Checklist
.h,.cpp,.cs,.ps1and.psm1files have the correct copyright headerWIP:or[ WIP ]to the beginning of the title (theWIPbot will keep its status check atPendingwhile the prefix is present) and remove the prefix when the PR is ready.- [ ] Issue filed:
(which runs in a different PS Host).