One of the more efficient approaches is as follows. With automatic reference counting (ARC),
NSMutableString *outputString = [[NSMutableString alloc] init];
NSUInteger loopMaximum = 10;
for (NSUInteger counter = 1; counter <= loopMaximum; counter++)
{
if (counter == 1)
{
[outputString appendFormat:@"%d", counter];
continue;
}
[outputString appendFormat:@", %d", counter];
}
NSLog(@"%@", outputString);
For manual reference counting (MRC) append [outputString release];
after the NSLog();
.
NSString
vs. NSMutableString
In the approach given in the question there is repeated creation NSString
objects as the answer is being constructed. The allocation and copying of memory is very slow, additionally since the objects begin produced are autoreleased, memory use will increase every time the loop iterates and will not be released until the next drain of an autoreleasepool. Instead, a better solution would be the use of NSMutableString
which is a subclass of NSString
designed to mutate/change and is much faster at appending characters to itself.
NSUInteger
vs. int
In the approach given in the question there is also use of int
. It is preferable to use NSInteger
and NSUInteger
as they avoid problems with execution on 32/64bit processors. Since there are no negative numbers the use of a unsigned variable (NSUInteger
)is also perferable as it gives a greater positive range.
Message Passing
Passing messages can become expensive particularly while iterating. By limiting the number of messages passed to 1 per iteration it reduces the amount of overhead incurred.