PowerShell For Loops Performance

Posted by : on

Category : powershell   scripts   system


PowerShell FOR Iterators

Small test to gauge the performance of the different types of For loops:

  1. For
  2. ForEach
  3. ForEachObject

Test code:

    $n = (1..1000) 
    function Test-for{
        $StopWatch = [system.diagnostics.stopwatch]::StartNew()
        For($i = 0 ; $i -lt 1000 ; $i++){
            $t = $i * 123456 - $i*123; $t = $t * $i * $i
        }
        $StopWatch.Stop()
        return $StopWatch.Elapsed.TotalMilliseconds
    }
    function Test-foreach{
        $StopWatch = [system.diagnostics.stopwatch]::StartNew()
        ForEach($i in $n){
            $t = $i * 123456 - $i*123; $t = $t * $i * $i
        }
        $StopWatch.Stop()
        return $StopWatch.Elapsed.TotalMilliseconds
    }
    function Test-foreachobject{
        $StopWatch = [system.diagnostics.stopwatch]::StartNew()
        $n | foreach-object {
            $t = $_ * 123456 - $_*123; $t = $t * $_ * $i
        }
        $StopWatch.Stop()
        return $StopWatch.Elapsed.TotalMilliseconds
    }
    Write-Host "==================" -f DarkRed
    Write-Host "   Test-foreach   " -f DarkYellow
    Write-Host "==================" -f DarkRed
    $v0=Test-for
    $v1=Test-foreach
    $v2=Test-foreachobject
    "Test-for          `t{0:n5}ms`nTest-foreach      `t{1:n5}ms`nTest-foreachobject`t{2:n5}ms`n------`nDiff fe/feo`t`t{3:n5}ms" -f $v0,$v1, $v2, ($v1-$v2)

Output this:

    ==================
       Test-foreach
    ==================
    Test-for                0.20910ms
    Test-foreach            0.16540ms
    Test-foreachobject      12.21550ms
    ------
    Diff fe/feo             -12.05010ms


About Guillaume Plante
Guillaume Plante

A developper with a passion for technology, music, astronomy and art. Coding range: hardware/drivers, security, ai,. c/c++, powershell

Email : guillaumeplante.qc@gmail.com

Website : https://arsscriptum.ddns.net

Useful Links