Jane_Meng
Jane_Meng

Reputation: 759

what's the difference between methods dictionary and dictionaryWithCapacity?

what's the difference between [NSMutableDictionary dictionary] and [NSMutableDictionary dictionaryWithCapacity:10]?

which one is better?

Upvotes: 3

Views: 1011

Answers (2)

Daryl Teo
Daryl Teo

Reputation: 5495

dictionaryWithCapacity is better if you know how many elements you are going to put in at the start. This means it can immediately allocate the required amount of space for your items.

It does not prevent you from adding more. It just means that if you exceed the allocated amount, it will have to allocate more, which may be more resource intensive.

On the flipside, if you don't know how many items you need, and you allocate too much space, you're not being memory efficient which is very important in mobile devices.

I don't have any benchmarks, but I don't believe the different is terribly huge, so I wouldn't be too fussed.

Upvotes: 3

jrturton
jrturton

Reputation: 119242

dictionaryWithCapacity will come back to bite you when you end up putting too much in there, or wasting space if you don't put enough in there. I would always use dictionary unless I was hitting specific memory or performance problems and dictionary appeared to be the cause of them. Otherwise it's just unnecessary complexity.

Upvotes: 0

Related Questions