Reputation: 283
I want to create a string. Based on condition I have to append some extra string. In this case which is preferred to use? Whether creating two different strings based on condition or creating mutable string to append a new string based on condition ?
EX
if(a==1)
{
String = "apple seed"
}
else
{
String = "apple"
}
Or
NSMutableString *string ;
string = @"apple";
if( a==1)
{
[string appendString:@"seed"]
}
Upvotes: 0
Views: 198
Reputation: 53000
A string literal, like your @"apple"
, is a compile-time constant so assigning a string literal to a variable of type NSString *
is a cheap operation.
So for your particular examples the first selects one of two simple assignments, while the second can do a simple assignment and a method call - which is clearly going to take a little more time.
That said a "little more" on a modern computer is not long. Beware of optimising prematurely; it is far better to write code that is clear and understandable to you first and concern yourself over performance of minutiae later if needed (this is not an excuse to write poor algorithms or intentionally bad code of course).
HTH
Upvotes: 1