0

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?

stephen
  • 1,039
  • 14
  • 31

2 Answers2

2

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

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

Catfish_Man
  • 41,261
  • 11
  • 67
  • 84
  • is there any documentation to support this claim? – stephen May 04 '13 at 06:50
  • @stephen Check the `CFStringRef` source at opensource.apple.com. While a `NSString` is a class cluster, chances are that you are going to end up invoking that implementation. – JustSid May 04 '13 at 06:52
  • There's the CFString source, which is OSS. That doesn't cover all NSString implementations though; you'd need to disassemble Foundation for those (Hopper is a good tool for that). – Catfish_Man May 04 '13 at 06:53
  • Actually paxdiablo is totally right. My answer was for -isEqualToString:, not -compare: – Catfish_Man May 04 '13 at 07:01
  • 1
    -compare: ends up calling CFStringCompareWithOptionsAndLocale, which can be found here: http://opensource.apple.com/source/CF/CF-744.18/CFString.c – Catfish_Man May 04 '13 at 07:03