PowerShell – Break vs. Continue Usage

For this example, we create two ArrayList objects and add a couple ints to them to run a loop to see if the value matches between the two and either continues a loop or breaks out of a loop:

$arraylist1 = New-Object -TypeName System.Collections.ArrayList
$arraylist1.Add(1) | Out-Null
$arraylist1.Add(2) | Out-Null
$arraylist1.Add(3) | Out-Null
$arraylist2 = New-Object -TypeName System.Collections.ArrayList
$arraylist2.Add(1) | Out-Null
$arraylist2.Add(2) | Out-Null
$arraylist2.Add(3) | Out-Null
Sample code for ‘continue’:
foreach ($item in $arraylist1)
{
    Write-Output -InputObject "item is: $item"
    foreach ($subitem in $arraylist2)
    {
        Write-Output -InputObject "subitem is: $subitem"
        if ($item -eq $subitem)
        {
            Write-Output -InputObject "$item matches $subitem! Continuing!"
            continue
        }
    }
}

…Which outputs:

item is: 1
subitem is: 1
1 matches 1! Continuing!
subitem is: 2
subitem is: 3
item is: 2
subitem is: 1
subitem is: 2
2 matches 2! Continuing!
subitem is: 3
item is: 3
subitem is: 1
subitem is: 2
subitem is: 3
3 matches 3! Continuing!
Sample code for ‘break’:
foreach ($item in $arraylist1)
{
    Write-Output -InputObject "item is: $item"
    foreach ($subitem in $arraylist2)
    {
        Write-Output -InputObject "subitem is: $subitem"
        if ($item -eq $subitem)
        {
            Write-Output -InputObject "$item matches $subitem! Breaking!"
            break
        }
    }
}

…which outputs:

item is: 1
subitem is: 1
1 matches 1! Breaking!
item is: 2
subitem is: 1
subitem is: 2
2 matches 2! Breaking!
item is: 3
subitem is: 1
subitem is: 2
subitem is: 3
3 matches 3! Breaking!

What can you use this for or when should I use what one? It depends on your use case. 🙂

Advertisements

PowerShell – Array vs. ArrayList Performance

Let’s take a look at performance when dealing with looping over an array variable; adding a new item and overall performance.
A standard array object in PowerShell is of a fixed size when created and cannot expand automatically. When you use the “+=” operator to append an entry, a new array object is created in memory with the additional overall previous array object. This leads to a large performance hit when dealing with a large number of items and increased memory consumption. For example:


$ArrayList = New-Object -TypeName 'System.Collections.ArrayList';
$Array = @();


Measure-Command
{
for($i = 0; $i -lt 10000; $i++)
{
$null = $ArrayList.Add("Adding item $i")
}
};
Measure-Command
{
for($i = 0; $i -lt 10000; $i++)
{
$Array += "Adding item $i"
}
};

Recommendation: use generics!