How to compare two NSString efficiently
I know it is possible to use the methods compare:
and isEqua开发者_如何学PythonlToString:
, and I suppose isEqualToString is the most efficient method If you know it´s an string. But my question is, is there another way to do it more efficiently? Like comparing char by char or something like that.
By reading the documentation:
The comparison uses the canonical representation of strings, which for a particular string is the length of the string plus the Unicode characters that make up the string. When this method compares two strings, if the individual Unicodes are the same, then the strings are equal, regardless of the backing store. “Literal” when applied to string comparison means that various Unicode decomposition rules are not applied and Unicode characters are individually compared. So, for instance, “Ö” represented as the composed character sequence “O” and umlaut would not compare equal to “Ö” represented as one Unicode character.
and:
When you know both objects are strings, this method is a faster way to check equality than isEqual:.
it seems that it's the best method available, to compare strings and that it does exactly what you need, that is: first it checks for length (if 2 strings have different length, is not necessary to check each char contained), then if the length it's the same it compares each char. Simple and efficient!
isEqualToString:
is faster if you know both objects are strings, as the documentation states.
You could try converting both string to C strings and then use strcmp. Doubt it'll actually be any quicker though.
char *str1 = [myNSString1 UTF8String];
char *str2 = [myNSString2 UTF8String];
BOOL isEqual = strcmp(str1,str2);
精彩评论