NSString - stringByAppendingString vs. appendString
Posted: Sat Sep 11, 2004 1:09 pm
When concatenating strings, appendString can outperform stringByAppendingString significantly. The appended demo code runs eight times faster with the mutable variety.
This was tested on a G5 running 10.3.5.
This was tested on a G5 running 10.3.5.
Code: Select all
#import <Foundation/Foundation.h>
NSString *foo( NSString *s, int times)
{
NSMutableString *string;
unsigned int i;
string = [NSMutableString string];
for( i = 0; i < times; i++)
[string appendString:s];
return( string);
}
NSString *bar( NSString *s, int times)
{
NSString *string;
unsigned int i;
string = @"";
for( i = 0; i < times; i++)
string = [string stringByAppendingString:s];
return( string);
}
#define LOOPS 100000
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSAutoreleasePool * pool2;
unsigned int i;
NSLog( @"Start mutable");
for( i = 0; i < LOOPS; i++)
{
pool2 = [[NSAutoreleasePool alloc] init];
foo( @"foo", 100);
[pool2 release];
}
NSLog( @"End mutable");
NSLog( @"Start immutable");
for( i = 0; i < LOOPS; i++)
{
pool2 = [[NSAutoreleasePool alloc] init];
bar( @"bar", 100);
[pool2 release];
}
NSLog( @"End immutable");
[pool release];
return 0;
}