Skip to content

Assigning the result of an addition (+ operator) with an IList LHS back to that LHS should preserve the list (collection) type #5805

Closed

Description

The following idioms should work generically with extensible collections that implement the IList interface and therefore have an .Add(Object) method.

# The following should both call $list.Add($newElement) behind the scenes:
$list = $list + $newElement
$list += $newElement

This would match the current array behavior (although a new array is created every time, given that arrays are fixed-size collections), as well as the behavior with hashtables (with hashtables as the RHS values too).

The current behavior is unexpected:

  • with an unconstrained variable: quietly converts the LHS to an array:
$list = [System.Collections.ArrayList] (1, 2)
$list += 3  # !! Quietly converts the ArrayList to Object[]
$list.GetType().Name . # !! Object[] 
  • with a type-constrained variable: creates a new instance
[System.Collections.ArrayList] $list = 1, 2 # type-constrained ArrayList
$orgList = $list # save reference to original list
$list += 3  # !! Quietly creates a *new instance*
[object]::ReferenceEquals($list, $orgList) # !! $False

Environment data

PowerShell Core v6.0.0-rc.2 (v6.0.0-rc.2) on macOS 10.13.2

Activity

  1. iSazonov commented on Jan 6, 2018

    @iSazonov
    Collaborator

    😄 Once I opened the case on Connect site and this case was closed "by design". It seems now we ready implement this enhancement.

  2. added
    WG-Engine
    Issue-Discussion
    on Jan 6, 2018
  3. iSazonov commented on Jan 6, 2018

    @iSazonov
    Collaborator

    Steve Lee (@SteveL-MSFT) Could you please consider this on PowerShell committee with #5643?

  4. added
    Review - Committee
    on Jan 8, 2018
  5. bergmeister commented on Jan 8, 2018

    @bergmeister
    Contributor
  6. daxian-dbw commented on Jan 9, 2018

    @daxian-dbw
    Member

    Does $list + $newElement always result in $list.Add($newElement) and then return $list, or only $list += $newElement and $list = $list + $newElement result in $list.Add($newElement)?

    If it's the latter, will $list + $newElement still return an object array? Then comparing $newlist = $list + $newElement with $list = $list + $newElement, the behavior of binary add needs to be different in those two cases, which in my opionion might be pretty hacky in imeplementation.

    I thought about having $list + $newElement always result in $list.Add($newElement) and then return $list, when it's able to. The potential problem is that an operand ($list) would be changed in the binary add operation, and I'm not sure whether that would be a bad UX.

    We also need to think about the consistency with Hashtable add operation. As shown in the example scripts below, adding two dictionary always creates a new Hashtable instance, and $hash1 += $hash2 will also result in a new Hashtable assigned to $hash1.

    $h = @{ name = "hello" }
    $s = @{ blah = "world" }
    $m = $h + $s # new Hashtable is created
    [System.Object]::ReferenceEquals($m, $h) #  False
    [System.Object]::ReferenceEquals($m, $s) # False
    
    $oldh = $h
    $h += $s # create new Hashtable
    [System.Object]::ReferenceEquals($h, $oldh) # False
    
  7. mklement0 commented on Jan 10, 2018

    @mklement0
    ContributorAuthor

    Does $list + $newElement always result in $list.Add($newElement)

    No - only if you assign back to the same variable; with the exception of the <op>= compound operators, operators shouldn't modify their operands in place as a side effect - that would indeed be unexpected.


    Yes, even though hashtables commendably do preserve the LHS type, they currently always create a new instance, as you demonstrate.

    I suppose one way to resolve this - if it's not too risky in terms of backward compatibility - is to update hashtable LHSs in place too, if self-assignment is involved.

    Resolving in the opposite direction - also always creating new instances for lists - would defeat the purpose of allowing efficient, incremental construction of (large) lists via +, as suggested in #5643 (my guess is that this is less of a concern with hashtables, as they typically don't grow too large).


    Perhaps there are implementation difficulties and even conceptual barriers I'm not considering; I guess we need to decide what specific expression forms to apply the proposed behavior to.

    $list += ... is unambiguous, but things get trickier with $list = ...:

    $list = $list + ... is the equivalent of the above; $list = ($list + ...) should be the same, but what about other variations, such as $list = $($list + ... ) or $list = @($list + ... )?

    There is also the other array-aware operator, * (am I missing others?): $list *= 2 should by analogy also append in place.

    In the end it must be reasonably obvious when in-place updating occurs and when not - though casual users may not care.

  8. added
    Breaking-Change
    Committee-Reviewed
    Up-for-Grabs
    and removed
    Review - Committee
    on Jan 17, 2018
  9. SteveL-MSFT commented on Jan 17, 2018

    @SteveL-MSFT
    Member

    @PowerShell/powershell-committee reviewed this and agreed that we should adopt only the +=, *=, and -= (if possible) syntax as they are unambiguous. Although technically a breaking change, it should not functionally affect most users other than giving them a perf benefit.

  10. lzybkr commented on Jan 18, 2018

    @lzybkr
    Contributor

    Note to whoever decides to implement this - as currently implemented, the binary operation binder knows nothing about assignment, so care is required to restrict this to += and not +.

    I do have a slight concern that by adding operator support, we'll make it much easier to make assumptions about how adding to lists works - e.g. if I add 2 lists - is that concatenation? Probably not, but if you don't introduce another operator, it will trip people up.

  11. daxian-dbw commented on Jan 18, 2018

    @daxian-dbw
    Member

    I can take a stab at += and *= as I have some code for this when working on the ListExpression.

    we'll make it much easier to make assumptions about how adding to lists works - e.g. if I add 2 lists - is that concatenation?

    Not sure I completely understand what you mean :) Adding two lists is kinda concatenation today -- it creates a new array containing all the elements from those 2 lists. So I think $list += $list2 should be adding the elements from $list2 to $list.

  12. 9 remaining items

  13. PetSerAl commented on Feb 19, 2018

    @PetSerAl
    Contributor

    Ideally, you never need to call methods - that's what cmdlets are for.

    So, this would be ideal solution:

    Add-ElementToList -List $List -Element $Element
  14. mklement0 commented on Feb 20, 2018

    @mklement0
    ContributorAuthor

    True, but let's focus on the important parts first:

    The cryptic 1 + 1 should really be:

    Add-Item -LeftOperand 1 -RightOperand 1

    For power users (method actors, if you will):

    1.Add(1)
  15. mklement0 commented on Feb 20, 2018

    @mklement0
    ContributorAuthor

    Kidding aside:

    Tcl is an example of a language where everything is invoked with shell-like (argument-mode) syntax and there's something to be said for this simplification.
    Clearly, though, that is not the direction PowerShell chose.

    Instead, PowerShell uses operators to provide convenient abstractions: Much of what requires method calls in, say, C#, is provided via operators such as -join, -split, -replace, ...

    To be clear: I'm not saying that you should avoid method calls - full access to the .NET Framework is a wonderful ability that sets PowerShell apart from other shells - I'm saying that you shouldn't have to call methods for basic operations, as calling methods is an advanced skill, both for syntactic reasons and having to know another knowledge domain.

    Let's take PowerShell's array handling, for example:

    The wonderfully simple construction of arrays (1, 2) and the ability to concatenate them by operator (1, 2 + 3, 4), to test for membership (1 -in 1, 2), ..., shields you from having to know the underlying [object[]] .NET type, and for most array uses you never need to call its methods.

    To combine convenient abstraction with reasonable performance when it comes to gradually building arrays ($a += ...), PowerShell should have implemented all of the above as [List[object]] (or at least [ArrayList]) rather than [object[]] from the get-go, but it sounds like it's too late to change that, at least based on the current assessment (is the future here yet?).

    The best we can do now is to provide a PowerShell-like way to construct a list ([list] (1, 2, 3) currently being discussed) and then provide the same syntactic convenience as for arrays - with the notable addition of making += extend the list in place.


    As an aside: consider how PowerShell's one foray into method syntax has fared; the (confusingly named) .ForEach() and .Where() collection operators never gained traction.

  16. PetSerAl commented on Feb 23, 2018

    @PetSerAl
    Contributor

    Michael Klement (@mklement0)
    For me what you are proposing is abusing operators. It is like C++ repurpose bit-shift operators for input-output handling. I do not like to have such thing in PowerShell. From previous .NET/C# experience I have expectation (IMO, reasonable), that there are some boundaries for expected operators behavior in .NET environment.

    • a += b should be semantically equivalent to a = a + b.
      C#, for example, does not even allows to overload += directly.
    • Operators should not visible modify theirs arguments.
      C# guides discourage defining operators for mutable types in the first place.

    I would understand breaking that boundaries if in return that provide very good benefits, which can not be achieved otherwise. But what we have there?

    You would not get any performance benefits unless user use some other type of collection instead of default array. So, instead of array we can provide for users PowerShell own list implementation, which would be friendly to repeatable += call and does not require sacrifice of operators sanity.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    
    public class ListWithFastAddition : IList<object>, IReadOnlyList<object>, IList, ICloneable {
        public static ListWithFastAddition operator +(ListWithFastAddition list, object item) {
            if(list==null) {
                throw new ArgumentNullException(nameof(list));
            }
            ListWithFastAddition result = list.Clone();
            result.Add(item);
            return result;
        }
    
        private List<object> list;
        private int count;
    
        public ListWithFastAddition() : this(new List<object>(), -1) { }
        private ListWithFastAddition(List<object> list, int count) {
            this.list = list;
            this.count = count;
        }
    
        public object this[int index] {
            get => index<Count ? list[index] : throw new ArgumentOutOfRangeException(nameof(index));
            set {
                if(OwnList) {
                    list[index] = value;
                } else if(index>=0 && index<count) {
                    list = list.GetRange(0, count);
                    count = -1;
                    list[index] = value;
                } else {
                    throw new ArgumentOutOfRangeException(nameof(index));
                }
            }
        }
        public int Count => OwnList ? list.Count : count;
        public bool IsReadOnly => false;
        private bool OwnList => count==-1;
    
        public void Add(object item) {
            if(OwnList) {
                list.Add(item);
            } else if(count==list.Count) {
                list.Add(item);
                count = list.Count;
            } else {
                list = list.GetRange(0, count);
                count = -1;
                list.Add(item);
            }
        }
        public void Clear() {
            if(OwnList) {
                list.Clear();
            } else {
                list = new List<object>();
                count = -1;
            }
        }
        public ListWithFastAddition Clone() {
            if(OwnList) {
                count = list.Count;
            }
            return new ListWithFastAddition(list, count);
        }
        public bool Contains(object item) => IndexOf(item) >= 0;
        public void CopyTo(object[] array, int index) => list.CopyTo(0, array, index, Count);
        public IEnumerator<object> GetEnumerator() => OwnList ? list.GetEnumerator() : list.Take(count).GetEnumerator();
        public int IndexOf(object item) => list.IndexOf(item, 0, Count);
        public void Insert(int index, object item) {
            if(OwnList) {
                list.Insert(index, item);
            } else if(index==count && count==list.Count) {
                list.Insert(index, item);
                count = list.Count;
            } else if(index>=0 && index<=count) {
                list = list.GetRange(0, count);
                count = -1;
                list.Insert(index, item);
            } else {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
        }
        public bool Remove(object item) {
            if(!OwnList) {
                list = list.GetRange(0, count);
                count = -1;
            }
            return list.Remove(item);
        }
        public void RemoveAt(int index) {
            if(OwnList) {
                list.RemoveAt(index);
            } else if(index>=0 && index<count) {
                list = list.GetRange(0, count);
                count = -1;
                list.RemoveAt(index);
            } else {
                throw new ArgumentOutOfRangeException(nameof(index));
            }
        }
    
        bool IList.IsFixedSize => false;
        int IList.Add(object item) {
            Add(item);
            return Count-1;
        }
        void IList.Remove(object item) => Remove(item);
        bool ICollection.IsSynchronized => false;
        object ICollection.SyncRoot => throw new NotImplementedException();
        void ICollection.CopyTo(Array array, int index) => CopyTo((object[])array, index);
        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
        object ICloneable.Clone() => Clone();
    }
    
    public class ListWithFastAdditionWrapper {
        public static ListWithFastAdditionWrapper operator +(ListWithFastAdditionWrapper wrapper, object item) {
            if(wrapper==null) {
                throw new ArgumentNullException(nameof(wrapper));
            }
            return new ListWithFastAdditionWrapper(wrapper.list+item);
        }
    
        private readonly ListWithFastAddition list;
    
        public ListWithFastAdditionWrapper() : this(new ListWithFastAddition()) { }
        public ListWithFastAdditionWrapper(ListWithFastAddition list) {
            if(list==null) {
                throw new ArgumentNullException(nameof(list));
            }
            this.list = list;
        }
    
        public ListWithFastAddition List => list;
    }

    Here is some performance measurements (I use ListWithFastAdditionWrapper as PowerShell v5.1 do not want to use overloaded + operator for collection. Do not test on current Core version yet):

    1..100 | % {
        $a = [System.Collections.Generic.List[object]]::new()
        Measure-Command {
            for($i=0; $i -lt 100000; ++$i) { $a.Add($i) }
        } | % TotalMilliseconds
    } | Measure-Object -Minimum -Maximum -Average |
    % { '{0}|{2}|{1}' -f $_.Minimum, $_.Maximum, $_.Average }
    # 414,3723|476,15554|926,0292
    
    1..100 | % {
        $a = [System.Collections.ObjectModel.Collection[object]]::new()
        Measure-Command {
            for($i=0; $i -lt 100000; ++$i) { $a.Add($i) }
        } | % TotalMilliseconds
    } | Measure-Object -Minimum -Maximum -Average |
    % { '{0}|{2}|{1}' -f $_.Minimum, $_.Maximum, $_.Average }
    # 417,773|473,210506|788,7197
    
    1..100 | % {
    $a = [ListWithFastAddition]::new()
        Measure-Command {
            for($i=0; $i -lt 100000; ++$i) { $a.Add($i) }
        } | % TotalMilliseconds
    } | Measure-Object -Minimum -Maximum -Average |
    % { '{0}|{2}|{1}' -f $_.Minimum, $_.Maximum, $_.Average }
    # 420,6408|539,701283|930,5778
    
    1..100 | % {
    $a = [ListWithFastAddition]::new()
        Measure-Command {
            for($i=0; $i -lt 100000; ++$i) { $a=[ListWithFastAddition]::op_Addition($a, $i) }
        } | % TotalMilliseconds
    } | Measure-Object -Minimum -Maximum -Average |
    % { '{0}|{2}|{1}' -f $_.Minimum, $_.Maximum, $_.Average }
    # 487,4737|554,867155|794,9613
    
    1..100 | % {
        $a = [ListWithFastAdditionWrapper]::new()
        Measure-Command {
            for($i=0; $i -lt 100000; ++$i) { $a+=$i }
        } | % TotalMilliseconds
    } | Measure-Object -Minimum -Maximum -Average |
    % { '{0}|{2}|{1}' -f $_.Minimum, $_.Maximum, $_.Average }
    # 1241,2363|1317,614091|1632,8237
    
    1..10 | % {
        $a = @()
        Measure-Command {
            for($i=0; $i -lt 100000; ++$i) { $a+=$i }
        } | % TotalMilliseconds
    } | Measure-Object -Minimum -Maximum -Average |
    % { '{0}|{2}|{1}' -f $_.Minimum, $_.Maximum, $_.Average }
    # 891699,4145|914223,93279|955229,7854

    For me that is pretty reasonable performance.

    So, if PowerShell would provide its own list implementation, then calling methods would be no more advanced, than choosing different collection type to work with. In that case having += as shortcut for calling Add method would be unreasonable abuse of operators, IMO.

  17. mklement0 commented on Feb 25, 2018

    @mklement0
    ContributorAuthor

    PetSerAl

    a += b should be semantically equivalent to a = a + b.

    I agree.

    Operators should not visible modify theirs arguments.

    That's certainly preferable; my hitherto unstated assumption was that, regrettably, in-place modification was the only way to achieve reasonable performance.

    It sounds like you're saying that you found a way to achieve reasonable performance even without in-place modification.

    I can confirm that your code achieves a very impressive speed-up compared to the current use of += with arrays (by a factor of hundreds).

    • I haven't analyzed your code yet; can you summarize succinctly how you achieved that?

    • If there are no gotchas, your solution definitely has my vote:

      • Why shouldn't we try it in PowerShell Core yet?

      • What would it take to make [ListWithFastAdditionWrapper] unnecessary so that += can be used directly with [ListWithFastAddition]? Given the wrapper's performance impact (a factor of about 3, though arguably still negligible compared to current += performance), would that go away?

  18. PetSerAl commented on Feb 26, 2018

    @PetSerAl
    Contributor

    Michael Klement (@mklement0)

    I haven't analyzed your code yet; can you summarize succinctly how you achieved that?

    Basically it use shared list internally, but remembers how much items from shared list it owns.

    Why shouldn't we try it in PowerShell Core yet?

    Sorry my bad English. I mean I did not test it in Core yet.

    What would it take to make [ListWithFastAdditionWrapper] unnecessary so that += can be used directly with [ListWithFastAddition]? Given the wrapper's performance impact (a factor of about 3, though arguably still negligible compared to current += performance), would that go away?

    PowerShell should pick up overloaded + operation for collections, then using wrapper would be unnecessary. Although, my measurements shows that 3x performance impact caused by +=, but not by wrapper. If you call [ListWithFastAdditionWrapper]::op_Addition directly rather then +=, then it is as fast as [ListWithFastAddition]::op_Addition.

    Updated version of ListWithFastAddition.

  19. mklement0 commented on Mar 6, 2018

    @mklement0
    ContributorAuthor

    Steve Lee (@SteveL-MSFT):

    Unless someone sees a (fundamental) flaw in PetSerAl's implementation, can I suggest we revisit this issue based on the following proposal?

  20. iSazonov commented on Mar 7, 2018

    @iSazonov
    Collaborator

    Michael Klement (@mklement0) Could you please make a Pester test prototype for first point?

  21. SteveL-MSFT commented on Mar 8, 2018

    @SteveL-MSFT
    Member
  22. mklement0 commented on Mar 8, 2018

    @mklement0
    ContributorAuthor

    Ilya (@iSazonov): I think I'd rather hold off until we have consensus on the way forward.

  23. Jaykul commented on Apr 28, 2018

    @Jaykul
    Contributor

    This:

    PowerShell should pick up overloaded + operation for collections, then using wrapper would be unnecessary

  24. added
    Resolution-No Activity
    on Nov 16, 2023
  25. iRon7 commented on Feb 13, 2026

    @iRon7

    Taken that this issue is Up-for-Grabs but closed, it is unclear whether this is still on the radar...
    Now Improve Array BinaryAdd Method for object[] #23901 has been implemented for fixed arrays, I assume that improving the performance for the assignment by addition operator (+=) of objects with an IList - or IDictionary interface would be easier than #23901 taken the fact that these objects are not of fixed size.
    (Leaving the re-assigning $a = $a + $b discussion out of consideration)

    Note that the performance impact on using += is quiet high, especially on the hash tables (IDictionary):

    Tests
    $tests = @{
        'Array+=' = {
            param($count)
    
            $result = @()
            foreach($i in 1..$count) {
                $result += $i
            }
        }
        'IList.Add' = {
            param($count)
    
            $result = [Collections.Generic.List[int]]::new()
            foreach($i in 1..$count) {
                $result.Add($i)
            }
        }
        'IList+=' = {
            param($count)
    
            $result = [Collections.Generic.List[int]]::new()
            foreach($i in 1..$count) {
                $result += $i
            }
        }
        'IDictionary[]' = {
            param($count)
    
            $result = @{}
            foreach($i in 1..$count) {
                $result[$i] = $i
            }
        }
        'IDictionary.Add' = {
            param($count)
    
            $result = @{}
            foreach($i in 1..$count) {
                $result.Add($i, $i)
            }
        }
    
        'IDictionary+=' = {
            param($count)
    
            $result = @{}
            foreach($i in 1..$count) {
                $result += @{ $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
    }
    CollectionSize Test            TotalMilliseconds RelativeSpeed
    -------------- ----            ----------------- -------------
              1024 IDictionary[]                0.19 1x
              1024 IList.Add                    0.35 1.84x slower
              1024 IDictionary.Add              0.50 2.63x slower
              1024 Array+=                      0.74 3.89x slower
              1024 IList+=                      1.16 6.11x slower
              1024 IDictionary+=               39.17 206.16x slower
    
    
    CollectionSize Test            TotalMilliseconds RelativeSpeed
    -------------- ----            ----------------- -------------
              5120 IDictionary[]                0.71 1x
              5120 IDictionary.Add              1.41 1.99x slower
              5120 IList.Add                    1.50 2.11x slower
              5120 IList+=                     20.33 28.63x slower
              5120 Array+=                     21.51 30.3x slower
              5120 IDictionary+=             1880.89 2649.14x slower
    
    
    CollectionSize Test            TotalMilliseconds RelativeSpeed
    -------------- ----            ----------------- -------------
             10240 IDictionary[]                0.92 1x
             10240 IDictionary.Add              3.79 4.12x slower
             10240 IList.Add                    4.71 5.12x slower
             10240 IList+=                     71.91 78.16x slower
             10240 Array+=                     86.93 94.49x slower
             10240 IDictionary+=             5502.40 5980.87x slower
    

    You might correctly argue that $a += @{ a = 2 } is bad practice in production, but the fact is that syntax simply exists and that += @{ ... } is apparently quite often used (and more specific: an assignment by addition operator of a hashtable with a dynamic key).
    Also note that capturing this "bad practice" in e.g. the PSScriptAnalyzer is rather difficult as the problem is identifying whether the LHS is an array/hashtable

    Can this issue be reopened or should I consider creating a new one?

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

Metadata

Metadata

Labels

Breaking-ChangeCommittee-ReviewedIssue-DiscussionResolution-No ActivityUp-for-GrabsWG-Engine

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions