adrian Coye
adrian Coye

Reputation: 173

NSString internals - how does length works?

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

Upvotes: 3

Views: 979

Answers (5)

sbooth
sbooth

Reputation: 16976

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.

Upvotes: 7

fzwo
fzwo

Reputation: 9902

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

Upvotes: 1

user166390
user166390

Reputation:

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.

Upvotes: 8

Hot Licks
Hot Licks

Reputation: 47709

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.

Upvotes: 3

MByD
MByD

Reputation: 137312

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

Upvotes: 1

Related Questions