I want to see if stringA is equal to any of a list of strings -- string1, string2, string3. What's the most performant way to do the comparison?
Since my comparison list is rather small, I'm currently trying this:
- (BOOL) isStringInList:(NSString *)testString{
if ([testString caseInsensitiveCompare:@"string1"] == NSOrderedSame)
return YES;
else if ([testString caseInsensitiveCompare:@"string2"] == NSOrderedSame)
return YES;
else if ([testString caseInsensitiveCompare:@"string3"] == NSOrderedSame)
return YES;
return NO;
}
This obviously does not scale well if I have many strings to compare against. I'd prefer more of a method signature like this -(BOOL) isString:(NSString *)testString inList:(NSString *)listString where listString is a space-separated string of keywords.
Any thoughts on how to improve performance would be appreciated.
The most performant way is to construct an NSSet of the strings you want to compare against and use -member: to test. Once the set is constructed, this will be a constant-time test. If you have a space-separated list to start with, you can use
NSSet *set = [NSSet setWithArray:[listOfWords componentsSeparatedByString:@" "]]
Constructing the set will be linear on the size of the input string. If your set is the same every time, you can construct it once and hold on to the result. To do the actual test you can use
[set member:myWord]
If the result is nil, your word isn't in the set. If it's non-nil, it is. Note, this is a case-sensitive search. If you need case-insensitivity, then you should either lowercase or uppercase both the list of words and the input word before performing your test.
- (BOOL)isString:(NSString*)testString inList:(NSString*)listString
{
BOOL result = NO;
if (testString != nil)
{
NSRange range = [listString rangeOfString:testString];
result = (range.location != NSNotFound);
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With