elements = []
for x in range(10000):
elements.append(x)
The equivalent in Powershell
is very costly
$elements = @()
0..10000 | foreach-object {
$elements += $_
}
Array literals in PowerShell
use the type System.Array
which cannot increase size
This means "appending" to an array past capacity causes it to allocate an entirely new array -- then copying the full contents. Allocating memory is expensive.
Arrays in other languages like Python
or JavaScript
are more closely related to [Collections.Generic.List]
in powershell
or std::vector<t>
in c++
They allocate arrays larger than the current size needed. This means instead of 17,000
allocations -- you end up with far, far, fewer.
For details on when to use ArrayList
verses List<T>
and when to use HashTable
vs Dictionary<TKey, TValue>
see: