Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@"" versus [NSString string]

Tags:

objective-c

I'm trying to work out the pros and cons of @"" and [NSString string] as they appear to behave in a similar fashion. I guess I'm hoping [NSString string] returns a static value thus avoiding unnecessary string creation in memory. Can anyone shed some light as the documentation is inconclusive.

like image 444
RobCroll Avatar asked Jan 11 '12 08:01

RobCroll


2 Answers

It's quite probable that @"" == [NSString string] and therefore the decision is just a matter of style. Aha, it’s not:

NSLog(@"%i", @"" == @""); // 1
NSLog(@"%i", [NSString string] == [NSString string]); // 1
NSLog(@"%i", [[NSString string] stringByAppendingString:@"foo"] ==
             [@"" stringByAppendingString:@"foo"]); // 1
NSLog(@"%i", @"" == [NSString string]); // 0

But I can’t think of any use case where the difference would matter.

like image 160
zoul Avatar answered Sep 20 '22 12:09

zoul


@"" is a literal string and will exist throughout the execution of the application. [NSString string] is probably a dynamically allocated object (but may be optimized to not be) and so could (in theory) be collected during execution when no longer referenced. Both literal strings and dynamically allocated ones employ sharing internally, so two @"" or two [NSString string] are likely to return the same object - even if not in the same file - but there is no guarantee that they will. However they may not return the same object as each other.

Overall it doesn't matter, you should not rely on pointer equality for testing string equality.

Looking at the assembly code I'd guess @"" has the performance edge, but thinking that is important is really a case of premature optimization.

Just use @"", it has the merit of being short and clear.

like image 40
CRD Avatar answered Sep 20 '22 12:09

CRD