Skip to content

Instantly share code, notes, and snippets.

@santisq
Last active October 10, 2023 18:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save santisq/1dd35ba142ea6dc7ebd9f26184ddd13b to your computer and use it in GitHub Desktop.
performance test for List<T> and Array BinarySearch Method
[System.Collections.Generic.List[int]] $list = 0..10mb
[int[]] $arr = $list.ToArray()
$ran = 0..100 | ForEach-Object { Get-Random -Maximum 15mb }
$tests = @{
'Array.BinarySearch' = { [array]::BinarySearch($args[0], $args[1]) }
'Array.IndexOf' = { $args[0].IndexOf($args[1]) }
'List.BinarySearch' = { $args[0].BinarySearch($args[1]) }
'List.IndexOf' = { $args[0].IndexOf($args[1]) }
}
$result = foreach ($i in $ran) {
foreach ($test in $tests.GetEnumerator()) {
$params = $list, $i
if ($test.Key.StartsWith('Array')) {
$params = $arr, $i
}
[pscustomobject]@{
Test = $test.Key
Time = (Measure-Command { & $test.Value @params }).TotalMilliseconds
}
}
}
$average = $result | Group-Object Test | ForEach-Object {
$average = [Math]::Round([System.Linq.Enumerable]::Average([double[]] $_.Group.Time), 2)
[pscustomobject]@{
Test = $_.Name
Average = $average
RelativeSpeed = ''
}
} | Sort-Object Average
$average | ForEach-Object {
$relativespeed = $_.Average / $average[0].Average
$_.RelativeSpeed = [math]::Round($relativespeed, 2).ToString() + 'x'
}
$average
Test               Average RelativeSpeed
----               ------- -------------
List.BinarySearch     0.09 1x
Array.BinarySearch    0.15 1.67x
Array.IndexOf         3.63 40.33x
List.IndexOf          5.03 55.89x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment