Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Howiieque

macrumors regular
Original poster
Feb 1, 2009
120
0
i just want to have an empty NSMutableDictionary.

[[NSMutableDictionary alloc] init]

or

[[NSMutableDictionary] alloc] initWithCapacity:0]

it seems that both of them work.
could some one explain which one i should use.
thank you in advanced.:)
 
The plain -init version probably calls initWithCapacity with the default value. What that value may be, I'm not sure.

There's one more way by the way:

[NSMutableDictionary new];

which is a shorthand method for:

[[NSMutableDictionary alloc] init];
 
i just want to have an empty NSMutableDictionary.

[[NSMutableDictionary alloc] init]

or

[[NSMutableDictionary] alloc] initWithCapacity:0]

it seems that both of them work.
could some one explain which one i should use.
thank you in advanced.:)

I would speculate that the former creates a dictionary with the default capacity while the later will create one with a capacity of 0. Assuming you later want to put something in the dictionary you would be better off with the former.

I don't know anything about the implementation of NSMutableDictionary but I would guess that the capacity parameter controls how many buckets you get so setting this to too low a number will cause excessive collisions and destroy performance. In a trivial implementation of Dictionary then setting capacity to 0 would prevent you from putting anything in the dictionary at all however it's possible that dictionaries will dynamically adjust bucket count or the constructor has a minimum number of buckets to create. I haven't tried it.

HTH,

Andrew
 
@cqexbesd

The capacity parameter is just a hint to NSMutableDictionary. It is by no means limited to the initial size, and will dynamically expand.

The purpose for this is to avoid repeated grows when it is known beforehand that X number of items are going to be inserted.

@OP

This all means that if you aren't concerned about memory allocation / reallocation being an issue, then it doesn't really matter. AFAIK, -init is equivalent to -initWithCapacity:0.
 
thank you guys.
according to The Designated Initializer, init might be overridden. i was just not sure. thank you for your answers.:)
 
You can also use [NSMutableDictionary dictionary], if you want to use a convenience method.
 
thank you for your suggestion.:)
because some authors said that reduce using the auto release pool would benefit the performance, so i use the alloc and init.
 
Autorelease pools are fast, don't worry about it. If you find your app going slowly, you should use Shark and Instruments to find out why, and *then* make it fast.
 
You only really need to worry about the autorelease pool if you're low on memory and in the middle of a large loop.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.