Optimizing search in CFArray
I have sorted CFArray, and I need to find the index of a value. But I am also not sure if the value is in this array, so I need to know this too.
Right now I use this code:
NSInteger valueIndex;
BOOL valueExac开发者_Python百科tMatch = CFArrayContainsValue((CFArrayRef)sortedBorders, arrayRange, value);
if (valueExactMatch)
valueIndex = CFArrayGetFirstIndexOfValue((CFArrayRef)sortedBorders, arrayRange, value);
else
valueIndex = CFArrayBSearchValues((CFArrayRef)sortedBorders, arrayRange, value, (CFComparatorFunction) CFDateCompare, nil);
But as I understand, valueExactMatch is being calculated twice — once in CFArrayContainsValue, and once performing the actual search.
Can I optimize it using existing CFArray implementation?
CFArrayGetFirstIndexOfValue
returns -1 if there is no match, so you can use this like so:
NSInteger valueIndex = CFArrayGetFirstIndexOfValue((CFArrayRef)sortedBorders, arrayRange, value);
if (valueIndex == -1)
valueIndex = CFArrayBSearchValues((CFArrayRef)sortedBorders, arrayRange, value, (CFComparatorFunction) CFDateCompare, nil);
I don't have a machine with XCode handy, but this may also work:
Boolean found = false;
NSInteger valueIndex = CFArrayBSearchValues((CFArrayRef)sortedBorders, arrayRange, value, (CFComparatorFunction) CFDateCompare, nil);
if (valueIndex < CFArrayGetCount(sortedBorders) && CFArrayGetValueAtIndex(sortedBorders, valueIndex) == value)
found = true;
精彩评论