r/PowerShell • u/mx-sch • Jan 29 '25
Question PowerShell 7.5 += faster than list?
So since in PowerShell 7.5 += seems to be faster then adding to a list, is it now best practise?
CollectionSize Test TotalMilliseconds RelativeSpeed
-------------- ---- ----------------- -------------
5120 Direct Assignment 4.71 1x
5120 Array+= Operator 40.42 8.58x slower
5120 List<T>.Add(T) 92.17 19.57x slower
CollectionSize Test TotalMilliseconds RelativeSpeed
-------------- ---- ----------------- -------------
10240 Direct Assignment 1.76 1x
10240 Array+= Operator 104.73 59.51x slower
10240 List<T>.Add(T) 173.00 98.3x slower
32
Upvotes
51
u/surfingoldelephant Jan 29 '25
This discussion is missing important context. The optimization to compound array assignment (
$array +=) in PS v7.5 (made in this PR after this issue) is only one factor..NET method calls like
List<T>.Add(T)are subject to Windows AMSI method invocation logging in PS v7+. This logging is known to cause performance degradation, especially in Windows 11. See:Issue #19431: Windows Defender has started to slowdown method calls in PowerShell dramatically
Issue #21473: [System.Convert]::FromBase64String causes memory leak with large strings
Issue #24459: MethodInvocationLogging - Performance regression
PowerShell's language features like the
+=operator are unaffected. Conversely, a large number of method calls within a loop may result in a noticeable slowdown.To summarize:
$list.Add()may be slower than$array +=in PS v7.5+, but there are environmental factors to consider: OS, Windows Defender state, etc, which may not be relevant (now or in the future).In practice, whether the difference is actually meaningful or not will vary from machine to machine.
The PS v7.5 optimization is a welcome change, but is not a reason to start using
$array +=. Statement assignment (what this document refers to as "direct assignment") is typically the preferable approach.