开发者

Optimizing search in CFArray

开发者 https://www.devze.com 2023-03-23 21:05 出处:网络
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.

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号