This next program benchmarks Array.BinarySearch against Array.FindIndex. It generates a string array of 10000 random file names and sorts them.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
class Program
{
static string[] GetArray()
{
List<string> list = new List<string>();
for (int i = 0; i < 10000; i++)
{
list.Add(Path.GetRandomFileName());
}
string[] array = list.ToArray();
Array.Sort(array);
return array;
}
const int _max = 10000;
static void Main()
{
string[] array = GetArray();
var s1 = Stopwatch.StartNew();
// Version 1: use BinarySearch.
for (int i = 0; i < _max; i++)
{
int index1 = i % 10000;
string key = array[index1];
int index2 = Array.BinarySearch<string>(array, key);
if (index1 != index2)
{
throw new Exception();
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use FindIndex.
for (int i = 0; i < _max; i++)
{
int index1 = i % 10000;
string key = array[index1];
int index2 = Array.FindIndex(array, element => element == key);
if (index1 != index2)
{
throw new Exception();
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(
"0.00 ns"));
}
}
1336.09 ns BinarySearch
57243.46 ns FindIndex