17

If I take a following question. What is the best way to initialize NSMutableString Class? (All instance will be return at unexpected times... so I'll assume that the initialization as follows:)

  1. If I know in advance the amount of work. ( expected )

    NSMutableString *str1 = [NSMutableString stringWithString:@""];
    NSMutableString *str2 = [NSMutableString stringWithCapacity:0];
    NSMutableString *str3 = [NSMutableString stringWithCapacity:1000];
    NSMutableString *str4 = [NSMutableString string];
    
    for(int i = 0; i< 1000; i++)
    {
        //The following tasks.(Adding to the string to continue working.)
        [/*str1~str4*/ appendFormat:@"%d", i];
    }
    
  2. If I don't know in advance the amount of work. ( unexpected )

    NSMutableString *str1 = [NSMutableString stringWithString:@""];
    NSMutableString *str2 = [NSMutableString stringWithCapacity:0];
    NSMutableString *str3 = [NSMutableString stringWithCapacity:1000];
    NSMutableString *str4 = [NSMutableString string];
    
    for(int i = 0; i< /*a large of size(unpredictable)*/ ; i++)
    {
        //The following tasks.(Adding to the string to continue working.)
        [/*str1~str4*/ appendFormat:@"%d", i];
    }
    

Largely split into two when performing these tasks, What is the best way to initialize?

I sometimes when working with these task is also confusing.

7 Answers 7

15

Case 1

Of the options listed, I'd use:

NSMutableString *str3 = [NSMutableString stringWithCapacity:1000];

…if you know the destination size, or estimate it with a little room at the top and are able to quickly determine the exact size, or the size worst case scenario, this could save multiple reallocate and copy operations. If you don't know the size in the worst case scenario, or if it takes a lot of time to calculate, then you may as well use [NSMutableString string] or [NSMutableString new]. Also, *WithCapacity is a hint, which the frameworks are free to ignore.

Of course, the body of your loop and the size you reserve also implies that all the values are [0…9] (specifically, that all values consume one character), and you could in that case likely do far better by using format strings with more arguments. However, i is obviously larger than 9 for most iterations, and will consume on average 3 characters each, so 3000 would be a more appropriate reserve capacity for the exact code you posted.

Case 2

Of the options listed, I'd use:

NSMutableString *str4 = [NSMutableString string];

Even better, if you don't need to add it to an autorelease pool: [NSMutableString new] or [[NSMutableString alloc] init].

Other Notes

Yes, keeping objects out of autorelease pools (e.g. use alloc+init) can improve performance and reduce peak memory usage significantly. Sometimes, this is beyond your control, and in some environments (e.g. ARC), this may happen even though you use an autoreleased convenience constructor - e.g. [NSMutableString string].

The Faster Solution

Finally, if this case you have outlined really is a performance concern, the fastest way would be to create a char buffer on the stack and then create one NSString from the result of copying the numbers over to the char buffer. Assuming your ints are all 0-9, it would be very fast and easy, then simply create an NSString from the (terminated) cstring. You can even do this if the input size varies, or is very large (results in a very long string).

5
  • The difference in memory usage between an @autoreleasepool block and manually releasing at the end of the scope shouldn't be all that great. So unless you're peppering releases all through your code (which does free up the memory more quickly but IMO makes it harder to see whether you released it at all), I'm skeptical about the difference in most cases. Out of curiosity, do you have any hard numbers on this?
    – Chuck
    Dec 27, 2011 at 0:06
  • @Chuck that is, however, not typical real world execution - very very few developers explicitly create autorelease pools regularly (beyond entry of a new thread/program). so the pools and the dependencies of the objects become large often. there are also a number of factors which reduce performance, it's not simply allocation count. belief that one can/should be oblivious to what 'the system handles efficiently, and automatically' leads to problems (cont)
    – justin
    Dec 27, 2011 at 1:14
  • (cont) not unlike objc garbage collection activity requiring a significant amount of a process's CPU time (a real example from OS X). and yes, i've extensively optimized a number of cocoa programs. the short of it is: explicitly controlling and minimizing objects' lifetimes, using immutable types in the appropriate places, etc. can make a program's execution a few times faster. one link exists in Rickay's post (which you have also commented on, so... I would have assumed that you saw it).
    – justin
    Dec 27, 2011 at 1:15
  • I'm just skeptical that this isn't overkill most of the time. The link in Rickay's post states that this is an optimization and shows how to do it. It does not tell when or by how much this is better than judicious use of autorelease pools. It also recommends allocWithZone: and a somewhat iffy implementation of object pools. Anyway, if you've built up a very complex object graph with references outside the local scope, it really doesn't matter which release method you use, because those objects are not getting dealloced immediately no matter how you release them.
    – Chuck
    Dec 27, 2011 at 1:59
  • 1
    @Chuck it appears you are choosing to remain skeptical. and that last bit in your comment is wrong because a good number of transient objects are created in most cases, their destruction can happen sooner and their memory can be returned sooner. So let's say you build something complex, like a window or complex view, are there temporary, autoreleased objects that are created which don't need to be added to autorelease pools and don't need to live beyond the scope in which they are allocated? surely.
    – justin
    Dec 27, 2011 at 3:05
10

It doesn't really matter.

If you've optimized your program so far that this decision will have a measurable effect on its overall performance, pat yourself on the back or, as Sheldon from BBT would say, "have a chocolate!"

PS:
If you precisely know the size up front or have a really good estimate on it, then use that size in stringWithCapacity: or initWithCapacity: if you don't, then don't even bother — let the framework decide, it's pretty damn clever!

1
  • +1. Their specific cleverness is available for your inspection if you feel the need to inspect it (__CFStrNewCapacity() in opensource.apple.com/source/CF/CF-635/CFString.c). But this is not typically a place you should be trying to optimize. If you're creating so many strings that this matters, you'll get better performance by reusing your string objects than optimizing their initial creation.
    – Rob Napier
    Dec 26, 2011 at 22:51
4

Here is the shortest way:

NSMutableString *string = [@"" mutableCopy];
1
  • This requires making an empty NSString (@"") and then calling a method on it to convert it to a mutable. It's not efficient.
    – Alexander
    Aug 5, 2014 at 16:29
1
NSMutableString *str1 = [NSMutableString stringWithString:@""];

Bad, a NSString (@"") is pointlessly created, then copied into a new NSMutable String

NSMutableString *str2 = [NSMutableString stringWithCapacity:0];

Bad, a NSMutableString with 0 capacity will need to be inflated upon the first addition to it.

NSMutableString *str3 = [NSMutableString stringWithCapacity:1000];

Good, if 1000 has some significance (i.e. it's an expected size for the content you're working with).

NSMutableString *str4 = [NSMutableString string];

Good, using a convenience method, which is is like doing [NSMutableString alloc] init];

0

If you know the size upfront, use

 [NSMutableString stringWithCapacity: _Known_Size_];

If you don't know the size up front, use

 [NSMutableString stringWithCapacity: _small_number_];

Then the mutable string will grow as it needs to.

0

In Swift 5:

var mutableString = NSMutableString("")
-2

It is always better to allocate and initialize an object, not use a class method to create it (which puts it in the closest autorelease pool).

So,

NSMutableString* stringOne = [[NSMutableString alloc] initWithCapacity:capacity];

instead of

NSMutableString* stringTwo = [NSMutableString stringWithCapacity:capacity];

Just remember that you have to release stringOne when you are done with it, but not stringTwo, because the stringWithCapacity: class method returns an autoreleased object.

Read more about the topic here: http://www.mulle-kybernetik.com/artikel/Optimization/opti-5.html

3
  • Not always better, no. There are many cases where all it gets you is more LOC.
    – Chuck
    Dec 26, 2011 at 19:53
  • @Rickay, In what way is stringOne better than stringTwo?
    – Caleb
    Dec 26, 2011 at 20:11
  • It's not 'better,' but performance-wise it is more efficient to manually allocate and release the memory yourself. It is a little more code, but it is better if you are going to be allocating a lot of strings. Dec 26, 2011 at 22:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.