In my project I need to have a list of predefined prefix or suffix for string items, it can be either prefix or suffix, so that I can go through the items and check the prefix or suffix of each item, just wondering which is less expensive? It feels like hasPrefix:
is less expensive but I don't have any reference to support this.
Thanks
NSString
is "toll-free bridged" to CFStringRef
, so
you can check the implementation in
CFString.c.
The relevant functions are CFStringHasPrefix()
and CFStringHasSuffix()
, which call
CFStringFindWithOptionsAndLocale()
without or with the kCFCompareBackwards
flag.
As I understand the code, this flag has no influence on the performance, only some loop variables are initialized differently.
(But the general "disclaimer" applies here as well: You should profile your application and check if the prefix/suffix check is a performance bottleneck at all. If not, choose whatever is more logical or easier to maintain.)