Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Created May 27, 2019 18:13
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 IISResetMe/bcacc1dedabad997b7be18da82c90b98 to your computer and use it in GitHub Desktop.
Save IISResetMe/bcacc1dedabad997b7be18da82c90b98 to your computer and use it in GitHub Desktop.
Array Reversal in the pipeline
# terrible
function Sort-VarReverse {
# sorting rank = max
$rank = [int]::MaxValue
$input |Sort-Object {
# decrement $rank in parent scope, reversing the input order
(--(Get-Variable rank -Scope 1).Value)
}
}
# bad
function Sort-ListReverse {
begin {
$list = [System.Collections.ArrayList]::new()
}
process {
# insert at the top, reversing the input order
$list.Insert(0,$_)
}
end {
$list
}
}
# pretty good
function Sort-StackReverse {
begin {
$stack = [System.Collections.Stack]::new()
}
process {
$stack.Push($_)
}
end {
# enumerating the stack returns the items in reverse input order
$stack
}
}
$twentyThousand = 1..20KB
Measure-Command {
$twentyThousand |Sort-VarReverse
} |Select-Object @{N='Strategy';E={'Var'}},TotalMilliseconds
Measure-Command {
$twentyThousand |Sort-ListReverse
} |Select-Object @{N='Strategy';E={'List'}},TotalMilliseconds
Measure-Command {
$twentyThousand |Sort-StackReverse
} |Select-Object @{N='Strategy';E={'Stack'}},TotalMilliseconds
# Sample output
#
# Strategy TotalMilliseconds
# -------- -----------------
# Var 1887.6106
# List 175.9195
# Stack 18.7144
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment