开发者

NSString internals - how does length works?

开发者 https://www.devze.com 2023-03-18 20:54 出处:网络
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 /开发者_JS百科 count each time / count & cache the result.

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 /开发者_JS百科 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 the length message 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, not nil.)

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.


Here is how CFStringGetLength works:

(from http://opensource.apple.com/source/CF/CF-550.43/CFString.c)

/* Returns length; use __CFStrLength2 if contents buffer pointer has already been computed.
*/
CF_INLINE CFIndex __CFStrLength(CFStringRef str) {
    if (__CFStrHasExplicitLength(str)) {
        if (__CFStrIsInline(str)) {
                return str->variants.inline1.length;
        } else {
                return str->variants.notInlineImmutable1.length;
        }
    } else {
        return (CFIndex)(*((uint8_t *)__CFStrContents(str)));
    }
}

So it should be O(1) for all cases.


The two -- testing a NSString pointer for nil and testing the length of an NSString -- are not in any way equivalent. An NSString object with a zero length can exist, and a pointer to it will not compare equal to nil.

To my knowledge (and I'd be quite surprised to discover I was wrong), the length of an NSString is stored within the object as an efficiently-referenced property. Caching the length would generally be unnecessary complexity.


NSString is immutable class, so the length stays the same all of the time.


Addendum: Testing against [string length] evaluates to 0/nil/NO in both cases (string being nil and string having zero length).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号