Re: Adding spaces to an NSString
Re: Adding spaces to an NSString
- Subject: Re: Adding spaces to an NSString
- From: Jens Alfke <email@hidden>
- Date: Tue, 18 Mar 2008 22:42:13 -0700
On 18 Mar '08, at 5:51 PM, J. Todd Slack wrote:
I am just looking for the most efficient way
Some principles:
* Insertion into the middle of a string (or array) is inefficient.
It's faster to append.
* Creating new strings is inefficient (as with -
stringByAppendingString:).
* printf-like functions, like -appendFormat:, are very inefficient.
So one good way to do this is to create a new empty NSMutableString,
then loop through the characters of the original string (using -
characterAtIndex), and append each character, and then a space, to the
new mutable string.
The problem you run into with that is that there's no -
[NSMutableString appendCharacter:]. So instead you either have to call
-appendFormat: @"%c" (which is slow), or create a temporary two-
character NSString (which is also slow.)
If I really had to optimize this function, I'd create a new C array of
unichar[], copy the characters and spaces into it, and then create a
new NSString using -initWithCharacters:length:.
But keep in mind one of Knuth's (or was it Dijkstra's?) principles:
* Premature optimization is the root of all evil.
Another, more positive, way to express this is with the Extreme
Programming maxim:
* Do the simplest thing that could possibly work.
The idea is that you shouldn't invest the time and complexity it takes
to optimize code until you know that the performance of that code is
actually measurable at a macroscopic level. This string-stretcher
routine is slower when written in a naive way, but unless it gets
called tens of thousands of times in a row, no one will ever notice
the difference, and the time you would have spent optimizing it would
be better used somewhere else.
—Jens
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden