views:

197

answers:

2

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

+7  A: 

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"];
Ben Gottlieb
I see, yes that makes perfect sense, many thanks for an excellent answer. I will also shorten it as you pointed out to use the string literal directly.
fuzzygoat
To further explain, string literals uniqued and stored in the binary for your app at compile time and don't require an allocation each time you use the string. Definitely a big win for memory at the expense of a small amount of binary size.
Colin Barrett
+5  A: 

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.

zneak
Thank you for the excellent answer, I wish I could have picked both to be correct, very informative, much appreciated.
fuzzygoat