• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Adding spaces to an NSString
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

References: 
 >Re: Adding spaces to an NSString (From: "J. Todd Slack" <email@hidden>)

  • Prev by Date: Re: Breaking on console output?
  • Next by Date: Re: What is this invisible character?
  • Previous by thread: Re: Adding spaces to an NSString
  • Next by thread: Re: Adding spaces to an NSString
  • Index(es):
    • Date
    • Thread