Skip to content

+= copies array many times #23899

Closed

Description

@nohwnd

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:

https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs#L3519-L3536

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.

image

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

  1. added
    Issue-Enhancement
    Needs-Triage
    on Jun 6, 2024
  2. StartAutomating commented on Jun 7, 2024

    @StartAutomating
  3. rhubarb-geek-nz commented on Jun 7, 2024

    @rhubarb-geek-nz

    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.

  4. jborean93 commented on Jun 7, 2024

    @jborean93
    Collaborator

    I've opened #23901 which can take advantage of Array.Resize when the LHS of += is of object[] 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.

  5. SeeminglyScience commented on Jun 7, 2024

    @SeeminglyScience
    Contributor

    I suggest that syntax like += is for convenience, not performance.

    Sure, but in our case the implementation for += for arrays is arbitrarily exponentially worse than it needs to be.

    For example is it well-known that it is better to use StringBuilder that appending individual strings.

    While I do tend to use StringBuilder, it turns out the benefit over += isn't all that profound for most cases.

    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.

    fyi you'd really want to avoid New-Object for 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 })

  6. StartAutomating commented on Jun 7, 2024

    @StartAutomating

    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.

  7. SeeminglyScience commented on Jun 7, 2024

    @SeeminglyScience
    Contributor

    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

  8. rhubarb-geek-nz commented on Jun 7, 2024

    @rhubarb-geek-nz

    fyi you'd really want to avoid New-Object for perf

    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)

    === Amsi notification report content ===
    <System.Collections.ArrayList>.Add(<foo>)
    === Amsi notification report success: False ===
    
    === Amsi notification report content ===
    <System.Text.StringBuilder>.Append(<bar>)
    === Amsi notification report success: False ===
    
  9. iRon7 commented on Jun 7, 2024

    @iRon7

    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:

    $start = [GC]::GetTotalAllocatedBytes($true)
    
    $numbers = 1..10000 
    $newNumbers = @(foreach ($number in $numbers) { $number })
    
    $end = [GC]::GetTotalAllocatedBytes($true)
    
    "$([System.Math]::Round(($end-$start) / 1GB, 2)) GB"

    0 GB

    The performance might be a little less than using an Add method but there is no garbage left.

    Related:

  10. 237dmitry commented on Jun 7, 2024

    @237dmitry

    Question: Could [GC]::GetTotalAllocatedBytes($true) be using for native commands to determine their statistic?

    #!/usr/bin/env -S pwsh -nop
    
    $w = [Diagnostics.StopWatch]::new()
    $s = [GC]::GetTotalAllocatedBytes($true) / 1mb
    
    $w.Start()
    Invoke-Expression "$args"
    $w.Stop()
    
    "`n Memory  : {0:f2} Mb`n Duration: {1:m\:ss\.fff}`n" -f
        ([GC]::GetTotalAllocatedBytes($true) / 1mb - $s),
        $w.Elapsed
    
    $w.Reset()
  11. nohwnd commented on Jun 7, 2024

    @nohwnd
    CollaboratorAuthor

    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.

    GitHub
    Script, ScriptBlock and module performance profiler for PowerShell 5, and PowerShell 7. - GitHub - nohwnd/Profiler: Script, ScriptBlock and module performance profiler for PowerShell 5, and PowerS...
  12. 237dmitry commented on Jun 7, 2024

    @237dmitry

    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.

    By native I mean applications that do not depend on pwsh. For example I run previous script:

    $ script ps ax
    <output ps ax>
    
     Memory  : 0,07 Mb     # Does this value reflect the memory consumption of the /usr/bin/ps process or not?
     Duration: 0:00.017
    
    $ script gps
    <output Get-Process>
    
     Memory  : 6,08 Mb
     Duration: 0:00.092
    
  13. SeeminglyScience commented on Jun 7, 2024

    @SeeminglyScience
    Contributor

    GC.GetTotalAllocatedBytes will look at managed heap allocations. It won't show out of process allocations nor will it reflect memory allocated via glibc!*alloc or kernel32!LocalAlloc. Only memory managed by the CLR

  14. mklement0 commented on Jun 7, 2024

    @mklement0
    Contributor

    👍 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 #5643

  15. SeeminglyScience commented on Jun 11, 2024

    @SeeminglyScience
    Contributor

    The performance might be a little less than using an Add method

    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.

    but there is no garbage left.

    0..10000 just 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.

  16. nohwnd commented on Jun 12, 2024

    @nohwnd
    CollaboratorAuthor

    When I measure 1...10000 I see 0.31 MB, not 4 MB, which seems reasonably close to the actual array.

    function mem ($ScriptBlock, $Items) {
    
        $sw = [System.Diagnostics.Stopwatch]::new()
        $start = [GC]::GetTotalAllocatedBytes($true)
        $sw.Start()
        $null = & $ScriptBlock
        $sw.Stop()
        $end = [GC]::GetTotalAllocatedBytes($true)
    
        
    
        "time: $($sw.ElapsedMilliseconds) ms"
        $total = $end - $start
        "alloc: $([System.Math]::Round(($total / 1MB), 4)) MB"
    
        if ($Items) { 
            "$Items items: $($total / $Items) bytes per item"
        }
    }
    
    mem { $a = 1..10000 }
    
    time: 1 ms
    alloc: 0.3303 MB
  17. SeeminglyScience commented on Jun 12, 2024

    @SeeminglyScience
    Contributor

    When I measure 1...10000 I see 0.31 MB, not 4 MB, which seems reasonably close to the actual array.

    Sorry for not being clear, I meant 4mb from the example they were using:

    $start = [GC]::GetTotalAllocatedBytes($true)
    
    $numbers = 1..10000 
    $newNumbers = @(foreach ($number in $numbers) { $number })
    
    $end = [GC]::GetTotalAllocatedBytes($true)
    
    # Just changed this to mb so it didn't round down to zero
    "$([System.Math]::Round(($end-$start) / 1MB, 2)) MB"
  18. microsoft-github-policy-service commented on Jun 17, 2024

    @microsoft-github-policy-service
    Contributor

    📣 Hey Jakub Jareš (@nohwnd), how did we do? We would love to hear your feedback with the link below! 🗣️

    🔗 https://aka.ms/PSRepoFeedback

  19. removed
    Needs-Triage
    on Jun 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions