fuzzygoat
fuzzygoat

Reputation: 26223

iPhone alloc or string literals for NSString?

I have a quick question about the two examples below. Currently I am using the top example on the understanding that because of the iPhones limited resources I am better off allocating and releasing manually as apposed to using the bottom string literal example. Does anyone have a preference as to which one to go with?

if(activeSegment == 0) {
    NSString *newText = [[NSString alloc] initWithString:@"Hello World"];
    [helloLabel setText:newText];
    [newText release];
}

OR

if(activeSegment == 0) {
    NSString *newText = @"Hello World";
    [helloLabel setText:newText];
}

Personally I don't think it matters in this case as I am setting the text on a label which wont be freed until the application exits anyway.

gary

Upvotes: 2

Views: 781

Answers (2)

zneak
zneak

Reputation: 138261

Definitely the second one if it's just about memory optimization. The first one allocates a string in addition to the statically allocated one you init it with (plus the overhead of allocating an object on the heap).

NSString *newText = [[NSString alloc] initWithString:@"Hello World"];

This snippet allocates dynamically a copy of "Hello World", but "Hello World" has to exist somewhere to be copied from first. ;)

It should also be noted that the compiler will reuse the same references to identical strings whenever it can, so if you define five strings with "Hello World" as their contents, there will actually just be one.

Upvotes: 5

Ben Gottlieb
Ben Gottlieb

Reputation: 85542

The second option is definitely better. String literals are just pointers into your code, rather than allocated memory. The second version is a lot lower-weight. You could also just do:

[helloLabel setText: @"Hello World"];

Upvotes: 7

Related Questions