Just wondering if anyone can see a way to optimize this piece of code. It is a key piece of my program and needs to run as quickly as possible. The part of the code I am unsure of is the while loop for finding the nearest key -- but any assistance with optimizing the code would be appreciated.
// TODO: Move to snippets lib or create a new collection type that supports this feature
private string _getTrait(SortedList<decimal, string> thisList, decimal thisValue)
{
// Check to see if we need to search the list.
if (thisList == null || thisList.Count <= 0) { return null; }
if (thisList.Count == 1) { return thisList.Values[0]; }
// Setup the variables needed to find the closest index
int lower = 0;
int upper = thisList.Count - 1;
int index = (lower + upper) / 2;
// Find the closest index (rounded down)
bool searching = true;
while (searching)
{
int comparisonResult = Decimal.Compare(thisValue, thisList.Keys[index]);
if (comparisonResult == 0) { return thisList.Values[index]; }
else if (comparisonResult < 0) { upper = index - 1; }
else { lower = index + 1; }
index = (lower + upper) / 2;
if (lower > upper) { searching = false; }
}
// Check to see if we are under or over the max values.
if (index >= thisList.Count - 1) { return thisList.Values[thisList.Count - 1]; }
if (index < 0) { return thisList.Values[0]; }
// Check to see if we should have rounded up instead
if (thisList.Keys[index + 1] - thisValue < thisValue - (thisList.Keys[index])) { index++; }
// Return the correct/closest string
return thisList.Values[index];
}
I am using C#, .net4.0 -- I need to use a Generic SortedList ( http://msdn.microsoft.com/en-US/library/ms132319(v=vs.100).aspx )