Skip to content

Improve Array BinaryAdd Method for object[] - #23901

Merged
Dongbo Wang (daxian-dbw) merged 1 commit into
PowerShell:masterfrom
jborean93:array-add
Jun 17, 2024
Merged

Dongbo Wang (daxian-dbw) merged 1 commit into
PowerShell:masterfrom
jborean93:array-add

Conversation

@jborean93

@jborean93 Jordan Borean (jborean93) commented Jun 7, 2024 •

Copy link
Copy Markdown
Collaborator

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

$s = [gc]::GetTotalAllocatedBytes($true)

Measure-Command {
    & {
        $val = @()
        for ($i = 0; $i -lt 20000; $i++) {
            $val += $i
        }
    }
}

$e = [gc]::GetTotalAllocatedBytes($true);

Write-Host "Allocated Bytes $($e-$s)"

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.

jborean:~/dev/PowerShell$ TEST=true debug/pwsh -File jordan.ps1

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 795
Ticks             : 7950790
TotalDays         : 9.20230324074074E-06
TotalHours        : 0.000220855277777778
TotalMinutes      : 0.0132513166666667
TotalSeconds      : 0.795079
TotalMilliseconds : 795.079

Allocated Bytes 1604712232
jborean:~/dev/PowerShell$ debug/pwsh -File jordan.ps1

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 9
Milliseconds      : 145
Ticks             : 91453429
TotalDays         : 0.000105848876157407
TotalHours        : 0.00254037302777778
TotalMinutes      : 0.152422381666667
TotalSeconds      : 9.1453429
TotalMilliseconds : 9145.3429

Allocated Bytes 6372367600

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

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.
@fflaten

Frode Flaten (fflaten) commented Jun 7, 2024 •

Copy link
Copy Markdown
Contributor

People should still use an alternative like capturing the output from the pipeline or use List<T>.

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 🙌

@daxian-dbw

Copy link
Copy Markdown
Member

The Engine WG discussed this and agree with the change, and it is ready to be reviewed.

@iSazonov Ilya (iSazonov) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: interesting, have we such issues with Collection, List (and others IEnumarable-s?

@jborean93

Copy link
Copy Markdown
Collaborator Author

nit: interesting, have we such issues with Collection, List (and others IEnumarable-s?

Somewhat yes, at least the known size types (not IEnumerable) could be improved by providing the capacity on the newly generated list but that's somewhat unrelated to fixing arrays. I didn't touch the code for other IList types because I was unsure whether it was safe to do IList.Count to get the capacity needed.

@SeeminglyScience

Copy link
Copy Markdown
Contributor

I didn't touch the code for other IList types because I was unsure whether it was safe to do IList.Count to get the capacity needed.

I would lean toward "maybe, but out of scope for this PR" just to get the most common use case settled quickly.

@SeeminglyScience

Copy link
Copy Markdown
Contributor

People should still use an alternative like capturing the output from the pipeline or use List<T>.

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 🙌

To be fair, interactively it's really hard to beat statement capture (e.g. $a = foreach ($b in $c) { $b }). Super easy, and still pretty performant

@fflaten

Frode Flaten (fflaten) commented Jun 11, 2024 •

Copy link
Copy Markdown
Contributor

To be fair, interactively it's really hard to beat statement capture (e.g. $a = foreach ($b in $c) { $b }). Super easy, and still pretty performant

True. I'm usually a few foreach-loops deep or splitting into multiple arrays when I need += or List in which case it's easier to manage imo.

Either way, looking forward to this.

@daxian-dbw Dongbo Wang (daxian-dbw) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@daxian-dbw
Dongbo Wang (daxian-dbw) merged commit 6c66879 into PowerShell:master Jun 17, 2024
@daxian-dbw Dongbo Wang (daxian-dbw) added the CL-Engine Indicates that a PR should be marked as an engine change in the Change Log label Jun 17, 2024
@jborean93
Jordan Borean (jborean93) deleted the array-add branch June 17, 2024 23:24
@iRon7

iRon7 commented Aug 30, 2024 •

Copy link
Copy Markdown

This is a great improvement to PowerShell 🎉.

Btw. a similar issue exists for using the increase assignment operator (+=) to build a string. (see: https://stackoverflow.com/a/70093215/1701026)
I wonder if it be possible to do something similar there by first translating the (fixed) string into a StringBuilder object, add the strings, and rebuild the string (.ToString()) at the moment the variable is retrieved?

Stack Overflow
Like with numerics?

For example,

$string = "Hello"
$string =+ " there"
In Perl you can do

my $string = "hello"
$string .= " there"
It seems a bit verbose to have to do

$string = $string + " t...

@scriptingstudio

Matthew Gray (scriptingstudio) commented Feb 12, 2026 •

Copy link
Copy Markdown

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 hashtable is some kind of array as well, so it makes sense to include it to tests.

$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 slower

My 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
New features and changes released in PowerShell 7.5

@iRon7

This comment was marked as off-topic.

@scriptingstudio

Copy link
Copy Markdown

I don't see what you trying to compare here.

collection performance

$a += @{ a = 2 } is bad practice in production (good for demonstration), and hashtable.add is much slower than [] syntax

A hashtable differs in a way that it doesn't support duplicate keys (in fact, it is more like a HashSet)

duplication is not the case, just add a unique value for a key

@SeeminglyScience

Patrick Meinecke (SeeminglyScience) commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor

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.

@scriptingstudio

Matthew Gray (scriptingstudio) commented Feb 12, 2026 •

Copy link
Copy Markdown

I apologize for any unnecessary "noise" and misunderstanding. Perhaps the best place would be the Discussions section. But while reading article https://learn.microsoft.com/en-us/powershell/scripting/whats-new/what-s-new-in-powershell-75?view=powershell-7.5, the section about improving += seemed interesting to me, and that led me to this PR.
I use hashtable a lot for indexing and as a very fast object collector, and I just added a section to the test with hashtable, which showed an advantage over List<T>.
Using hashtable as a "list" of objects is not obvious, but it is very effective.

New features and changes released in PowerShell 7.5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CL-Engine Indicates that a PR should be marked as an engine change in the Change Log

Projects

None yet

Development

Successfully merging this pull request may close these issues.

+= copies array many times

7 participants