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.
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.
@""
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With