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?
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];
-
Looking for a general-purpose drop-in replacement for stringWithFormat... harder than it looks! – SG1 Dec 21 '12 at 20:58
-
-
@Danpe No, you don't need to release the char array, because it's not a pointer. It will be automatically released at the end of the function(if it is inside a function) or after each run of the loop(if it is inside in loop) – JMBise Oct 14 '13 at 12:24
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 !
-
-
2It was in a WWDC 2012 video. I'm going to rack my brains for which one it was now. TBC. – Daniel Nov 26 '12 at 19:11
-
Thanks. I'm interested in watching that video if you remember which one it was. – Stephen Melvin Nov 26 '12 at 19:13
-
4Okay got it: Session 212 Basics + Habits: Building Your Software To Last - at 13 minutes. developer.apple.com/videos/wwdc/2012/?include=212#212 – Daniel Nov 26 '12 at 19:36
myString = [NSString stringWithFormat:@"%@", "ABC"];
as I've seen many times here. It's totally wasted motion!) – Hot Licks Nov 26 '12 at 16:25NSString *str = [NSString stringWithFormat:@"%@", otherString];
do you? I've seen plenty of examples of that on stackoverflow... – trojanfoe Nov 26 '12 at 16:25