Skip to content

Instantly share code, notes, and snippets.

@potatoqualitee
Last active May 31, 2022 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save potatoqualitee/41fa05d4a7cc718c698fb49cfb215494 to your computer and use it in GitHub Desktop.
Save potatoqualitee/41fa05d4a7cc718c698fb49cfb215494 to your computer and use it in GitHub Desktop.
looping
$parms = @{
   Path        = "C:\windows\system32"
   Recurse     = $true
   ErrorAction = "SilentlyContinue"
}

Measure-Benchmark -RepeatCount 25 -Technique @{
    ForEachObject = { 
        Get-ChildItem @parms | ForEach-Object -Process {
            $null = $PSItem.Name
        }   
    }

    foreach = { 
        foreach ($file in (Get-ChildItem @parms)) {
            $null = $file.Name
        }
    }

    for = {
        $files = Get-ChildItem @parms
        for ($i=0; $i -lt $files.Length; $i++) {
            $null = $files[$i].Name
        }
    }

    dowhile = { 
        $i = 0
        $files = Get-ChildItem @parms
        do {
            $null = $files[$i].Name
            $i++
        } while ($i -lt $files.Length)
    }
    
    dountil = {
        $i = 0
        $files = Get-ChildItem @parms
        do {
            $i++
            $null = $files[$i].Name
        } until ($i -eq $files.Length)
    }

    foreachMethod = { 
        (Get-ChildItem @parms).foreach({ $null = $PSItem.Name })
    }

    GetEnumerator = {
        $file = (Get-ChildItem @parms).GetEnumerator()
        while ($file.MoveNext())
        {
           $null = $file.Name
        }
    }
}

And the results, as James suggested, for 25 reptitions.

Technique     Time            RelativeSpeed Throughput
---------     ----            ------------- ----------
dountil       00:00:24.711281 1x            1.01/s
dowhile       00:00:24.964245 1.01x         1/s
foreach       00:00:25.003148 1.01x         1/s
GetEnumerator 00:00:25.510600 1.03x         0.98/s
for           00:00:26.195856 1.06x         0.95/s
ForEachObject 00:00:27.603218 1.12x         0.91/s
foreachMethod 00:00:27.985550 1.13x         0.89/s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment