You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Assigning the result of an addition (+ operator) with an IList LHS back to that LHS should preserve the list (collection) type #5805
Breaking-Changebreaking change that may affect usersCommittee-ReviewedPS-Committee has reviewed this and made a decisionIssue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-No ActivityIssue has had no activity for 6 months or moreUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Enginecore PowerShell engine, interpreter, and runtime
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
Reacted by Ilya, Rain Sallow (/u/ta11ow), zett42 and iRon7
Reacted by Christoph Bergmeister and Rain Sallow (/u/ta11ow)
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
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.
@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.
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.
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.
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.
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.
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):
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.
Reacted by Michael Klement, Staffan Gustafsson, Rain Sallow (/u/ta11ow) and iRon7
Reacted by Staffan Gustafsson, Dongbo Wang and Rain Sallow (/u/ta11ow)
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?
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.
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):
Breaking-Changebreaking change that may affect usersCommittee-ReviewedPS-Committee has reviewed this and made a decisionIssue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-No ActivityIssue has had no activity for 6 months or moreUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Enginecore PowerShell engine, interpreter, and runtime
Activity
iSazonov commentedon Jan 6, 2018
😄 Once I opened the case on Connect site and this case was closed "by design". It seems now we ready implement this enhancement.
iSazonov commentedon Jan 6, 2018
Steve Lee (@SteveL-MSFT) Could you please consider this on PowerShell committee with #5643?
bergmeister commentedon Jan 8, 2018
Michael Klement (@mklement0) Awesome!
daxian-dbw commentedon Jan 9, 2018
Does
$list + $newElementalways result in$list.Add($newElement)and then return$list, or only$list += $newElementand$list = $list + $newElementresult in$list.Add($newElement)?If it's the latter, will
$list + $newElementstill return an object array? Then comparing$newlist = $list + $newElementwith$list = $list + $newElement, the behavior ofbinary addneeds to be different in those two cases, which in my opionion might be pretty hacky in imeplementation.I thought about having
$list + $newElementalways 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 += $hash2will also result in a new Hashtable assigned to$hash1.mklement0 commentedon Jan 10, 2018
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 *= 2should 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.
SteveL-MSFT commentedon Jan 17, 2018
@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.lzybkr commentedon Jan 18, 2018
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.
daxian-dbw commentedon Jan 18, 2018
I can take a stab at
+=and*=as I have some code for this when working on theListExpression.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 += $list2should be adding the elements from$list2to$list.9 remaining items
PetSerAl commentedon Feb 19, 2018
So, this would be ideal solution:
mklement0 commentedon Feb 20, 2018
True, but let's focus on the important parts first:
The cryptic
1 + 1should really be:For power users (method actors, if you will):
mklement0 commentedon Feb 20, 2018
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.PetSerAl commentedon Feb 23, 2018
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 += bshould be semantically equivalent toa = a + b.C#, for example, does not even allows to overload
+=directly.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.Here is some performance measurements (I use
ListWithFastAdditionWrapperas PowerShell v5.1 do not want to use overloaded+operator for collection. Do not test on current Core version yet):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 callingAddmethod would be unreasonable abuse of operators, IMO.mklement0 commentedon Feb 25, 2018
PetSerAl
I agree.
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?PetSerAl commentedon Feb 26, 2018
Michael Klement (@mklement0)
Basically it use shared list internally, but remembers how much items from shared list it owns.
Sorry my bad English. I mean I did not test it in Core yet.
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_Additiondirectly rather then+=, then it is as fast as[ListWithFastAddition]::op_Addition.Updated version of
ListWithFastAddition.mklement0 commentedon Mar 6, 2018
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?
make this issue just about preserving the LHS collection type - without in-place extending
make PetSerAl's list implementation the basis for the PowerShell-native list implementation proposed in PowerShell should support creating an List similar to how it supports arrays #5643
iSazonov commentedon Mar 7, 2018
Michael Klement (@mklement0) Could you please make a Pester test prototype for first point?
SteveL-MSFT commentedon Mar 8, 2018
cc Bruce Payette (@BrucePay)
mklement0 commentedon Mar 8, 2018
Ilya (@iSazonov): I think I'd rather hold off until we have consensus on the way forward.
Jaykul commentedon Apr 28, 2018
This:
iRon7 commentedon Feb 13, 2026
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[]
#23901has been implemented for fixed arrays, I assume that improving the performance for the assignment by addition operator (+=) of objects with anIList- orIDictionaryinterface would be easier than #23901 taken the fact that these objects are not of fixed size.(Leaving the re-assigning
$a = $a + $bdiscussion out of consideration)Note that the performance impact on using
+=is quiet high, especially on the hash tables (IDictionary):Tests
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
PSScriptAnalyzeris rather difficult as the problem is identifying whether the LHS is an array/hashtableCan this issue be reopened or should I consider creating a new one?