SoSleepy

Troy Bowman

Various Ways to Add Values to an Array

Declare an array of a fixed size.

$FixedArray = [int[]]::new($number)
# Example
$FixedArray = [int[]]:new(10)

# Prompt for the size of the fixed array.
$FixedArray = [int[]]::new((Read-Host "Enter the array size"))



Declaring empty arrays and then using += add values will add a significant penalty in the time to complete the operation. It takes 383 seconds to assign 100,000 values to an array using +=

 $Array = @()
 Measure-Command {foreach ($j in 1..100000) {$Array += Get-Random}} 



$FixedArraySize = [int[]]::new(100000)
Measure-Command {foreach ($j in 0..99999) {$FixedArraySize[$j] = Get-Random}}



The .Net List can be used when the size of an array is not known and needs fast addition and removal operation.

$List = [System.Collections.Generic.List[int]]::new()
Measure-Command {foreach ($j in 1..100000) {$List.Add((Get-Random))}}



$SortedSet = [System.Collections.Generic.SortedSet[int]]::new()
Measure-Command {foreach ($j in 1..100000) {$SortedSet.Add((Get-Random))}}

There is a significant time penalty when using a SortedSet compared to a .Net List or fixed array. So SortedSets should only be used when the data needs to be kept sorted at all times.

,

Leave a Reply

Your email address will not be published. Required fields are marked *