开发者

what's the difference between methods dictionary and dictionaryWithCapacity?

开发者 https://www.devze.com 2023-04-06 10:45 出处:网络
what\'s the difference between [NSMutableDictionary dictionary] and [NSMutableDictionary dictionaryWithCapacity:10]?

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

which one 开发者_开发问答is better?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号