Created
May 27, 2019 18:13
-
-
Save IISResetMe/bcacc1dedabad997b7be18da82c90b98 to your computer and use it in GitHub Desktop.
Array Reversal in the pipeline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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