I’ve a question about NSString internals.
I want to check a string length and basically I wanted to know if a NSString knows its length / count each time / count & cache the result.
Should I store it’s length and compute or call the length method each time ?
To test a string I can test against nil OR ask for it’s length.
if (str != nil) {
// compute
}
if ([str length]) {
// compute
}
Which one is the fastest ?
Which one is the more memory efficient ?
Thanks
Checking for
nil(“no object”) is most definitely not the same as sending thelengthmessage to the (NSString) object. Only one of the conditional checks is valid to test for an “empty” string. (An “empty” string is an object and, therefore, notnil.)The bigger question is: does NSString store a length or is it sentinel-terminated (like a “normal c string”)? NSString stores the length as an internal property so it,
length, is as O(1) operation.Happy coding.