Reputation: 33
I am wondering if there is a better way to convert int to string Basically I have a counter and a dictionary
//
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
int cnt = 0;
//
// insert an object
//
id object = [[[SomeObject alloc] init] autorelease];
NSString *key = [NSString stringWithFormat:@"%d", cnt++];
[dict setObject:object forKey:key];
The thing is converting int to string takes more time than I expected. So is there a better way to get around this?
Upvotes: 1
Views: 1140
Reputation: 3682
Interesting link about nsfoundation
Quote:
NSString creation is not particularly expensive, but when used in a tight loop (as dictionary keys, for example), +[NSString stringWithFormat:] performance can be improved dramatically by being replaced with asprintf or similar functions in C.
and code example:
NSString *firstName = @"Daniel";
NSString *lastName = @"Amitay";
char *buffer;
asprintf(&buffer, "Full name: %s %s", [firstName UTF8String], [lastName UTF8String]);
NSString *fullName = [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
free(buffer);
Upvotes: 1
Reputation: 18860
I suppose this is mildly faster:
NSString* yourString = [@(yourInteger) stringValue];
And this
[dict setObject:yourObj forKey:[@(yourInt) stringValue]];
Does look better than:
[dict setObject:yourObj forKey:[NSString stringWithFormat:@"%d",yourInt]];
But we're really splitting hairs here from both speed and style points of view.
Upvotes: 6
Reputation: 6363
Do you explicity need it as a string? Or maybe just use literals(note that it will be NSNumber in this case):
[dict setObject:object forKey:@(cnt++)];
Upvotes: 0