Question

String compares can be costly. There's some statistic floating around that says a very high percent of string compares can be eliminated by first comparing string sizes. So I'm curious to know whether the NSString compare: method takes this into consideration. Anyone know?

Was it helpful?

Solution

According to the sources here (which is just one implementation, others may act differently), compare doesn't check the length first, which actually makes sense since it's not an equality check. As it returns a less-than/equal-to/greater-than return code, it has to check the characters, even if the lengths are the same.

A pure isEqual-type method may be able to shortcut character checks if the lengths are different, but compare does not have that luxury.

It does do certain checks of the length against zero, but not comparisons of the two lengths against each other.

OTHER TIPS

Yes it does. It also checks for pointer equality before that (which covers the constant string case and some others due to string uniquing and the string ROM).

(edit) This answer applies to -isEqualToString:, not -compare:. I misread

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top