// time both searches (linear and binary (log)), and find optimal breakpoint - where to use which for maximal performance int FindOptimalBreakpointArray() { int optimalBreakpoint = 2; var random = new System.Random(); Stopwatch stopwatchLinear = new Stopwatch(); Stopwatch stopwatchBinary = new Stopwatch(); float lin = 0f; float log = 1f; // continue increasing "optimalBreakpoint" until linear becomes slower than log // result is around 15-16, varies a bit due to random nature of test while (lin <= log) { int numOfDiffArrays = 100; int numOfTestPerArr = 10000; // u = uniform grid, r = uniform random float u, r; ///Linear Search stopwatchLinear.Stop(); stopwatchLinear.Reset(); float[] items = RandomMath.IdentityArray(optimalBreakpoint); float selectedItem; //here just to simulate selecting from array float[] arr = new float[optimalBreakpoint]; for (int k = 0; k < numOfDiffArrays; k++) { RandomMath.RandomWeightsArray(ref arr, random); RandomMath.BuildCumulativeDistribution(arr); stopwatchLinear.Start(); for (int i = 0; i < numOfTestPerArr; i++) { u = i / (numOfTestPerArr - 1f); selectedItem = items[arr.SelectIndexLinearSearch(u)]; r = (float)random.NextDouble(); selectedItem = items[arr.SelectIndexLinearSearch(r)]; } stopwatchLinear.Stop(); } lin = stopwatchLinear.ElapsedMilliseconds; /// Binary Search stopwatchBinary.Stop(); stopwatchBinary.Reset(); for (int k = 0; k < numOfDiffArrays; k++) { RandomMath.RandomWeightsArray(ref arr, random); RandomMath.BuildCumulativeDistribution(arr); stopwatchBinary.Start(); for (int i = 0; i < numOfTestPerArr; i++) { u = i / (numOfTestPerArr - 1f); selectedItem = items[arr.SelectIndexBinarySearch(u)]; r = (float)random.NextDouble(); selectedItem = items[arr.SelectIndexBinarySearch(r)]; } stopwatchBinary.Stop(); } log = stopwatchBinary.ElapsedMilliseconds; optimalBreakpoint++; } return(optimalBreakpoint); }