AJ222
AJ222

Reputation: 1134

NSString stringWithFormat is slow

In Objective-C, the method stringWithFormat: seems to be extremely slow and is actually a large bottleneck in one of our apps (we used the profiler to find that out). Is there a way to optimise it or use some faster C code?

Upvotes: 4

Views: 2715

Answers (2)

JMBise
JMBise

Reputation: 690

Yes use sprintf in c http://www.cplusplus.com/reference/cstdio/sprintf/ after that push the char* in a NSString with [NSString stringWithUTF8:];

example:

char cString[255];
sprintf (cString, "%d", 36);
NSString* OCstring = [[NSString alloc] initWithUTF8String:cString];

Upvotes: 8

Daniel
Daniel

Reputation: 23359

If you're doing extensive string manipulations and operations - it sounds like you might well be doing so, and NSString really is becoming a bottleneck for your app, I recommend trying to use C++ for your string needs rather then C.

Apple admits that while NSString is great, it is top level, in fact, to make their autocorrect algorithm's for iOS they ran into a similar problem, NSString was too slow to compute and compare so many things. They then switched to C++ and got all the performance they needed.

Just a suggestion. You should definitely put up some code, I am surprised this is happening to you unless you're doing some awesome new feature !

Upvotes: 6

Related Questions