Boris Vidolov
Boris Vidolov

Reputation: 149

Performance impact of NSString:characterAtIndex in objective C

I am new to Objective C, coming from C++ & C# background. I need to do some string manipulation. As I need to operate at character level, I am concerned that making a function call for each character will be far too slow. E.g. in C/C++, when working with const char*, indexing is very fast. Is there any documentation that goes over the performance impact of methods like "charactersAtIndex"? Is the compiler smart enough to inline this method?

int current = 0;
NSString* str = @"....";//Long string
while (current < str.length && [str characterAtIndex:current] != ';')//function call at each character?
  ++current;

Upvotes: 1

Views: 575

Answers (1)

Soonts
Soonts

Reputation: 21936

You're correct, obj-c method calls are even more expensive than C++ virtual calls.

If you're concerned about the performance, you could query the length, then allocate buffer (depending on the expected length, either malloc or alloca), then call getCharacters:range: method to get C array of unicode characters in the string. Don't use UTF8String unless you're ready to link with something like IBM's ICU library to access individual characters.

Also, sometimes NSScanner class is helpful.

Upvotes: 2

Related Questions