Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
AJ222 Avatar asked Dec 08 '22 19:12

AJ222


2 Answers

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];
like image 155
JMBise Avatar answered Dec 11 '22 09:12

JMBise


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 !

like image 32
Daniel Avatar answered Dec 11 '22 08:12

Daniel