I’ve found some interesting behaviour in PowerShell Arrays, namely, if I declare an array as:
$array = @()
And then try to add items to it using the $array.Add("item") method, I receive the following error:
Exception calling “Add” with “1” argument(s): “Collection was of a fixed size.”
However, if I append items using $array += "item", the item is accepted without a problem and the “fixed size” restriction doesn’t seem to apply.
Why is this?
When using the
$array.Add()-method, you’re trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can’t be extended.$array += $elementcreates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the$array-variableSource: about_Arrays
+=is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:If that’s not possible, consider using a more efficient collection like
ListorArrayList(see the other answer).