I am refactoring code which contains many lines of NSString* image = [@"ipad_" stringByAppendingString:imageOrigName];
and wondered which is more optimized:
stringByAppendingString:
or
stringWithFormat:
In the first, you take one NSString
object and concatenate another onto its tail. In the second, you can use a formatter:
NSString* image = [NSString stringWithFormat:@"ipad_%@", imageOrigName];
The result is the same, but for optimization purposes, which is better?
For the above example, I would expect that a simple concatenation would be faster than having it parse the string for '%' symbols, find a matching type (NSString
for the %@
), and do all its background voodoo.
However, what happens when we have (sloppily written?) code which contains multiple stringByAppendingString
s?
NSString* remainingStr = [NSString stringWithFormat:@"%d", remaining];
NSString* msg = "You have ";
msg = [msg stringByAppendingString:remainingStr];
msg = [msg stringByAppendingString:@" left to go!"];
if (remaining == 0)
msg = [msg stringByAppendingString:@"Excellent Job!"];
else
msg = [msg stringByAppendingString:@"Keep going!"];
Here, a single stringWithFormat
(or initWithFormat
if we use [NSString alloc]
) would seem to be the smarter path:
NSString* encouragementStr = (remaining == 0 ? @"Excellent Job!" : @"Keep going!");
NSString* msg = [NSString stringWithFormat:@"You have %d left to go! %@", remaining, encouragementStr];
Thoughts? Sites/blogs that you've found that helps answer this?