Difference between literals and class methods for NSMutableArray and NSMutableDictionary [duplicate]

孤者浪人 提交于 2019-12-02 09:49:26

问题


When I started with OSX/iOS I used

    NSMutableArray *        a1 = [NSMutableArray arrayWithCapacity:123] ;
    NSMutableDictionary *   d1 = [NSMutableDictionary dictionaryWithCapacity:123] ;

Then I discovered the 'simpler' version

    NSMutableArray *        a2 = [NSMutableArray array] ;
    NSMutableDictionary *   d2 = [NSMutableDictionary dictionary] ;

I have now moved to:

    NSMutableArray *        a3 = [@[] mutableCopy] ;
    NSMutableDictionary *   d3 = [@{} mutableCopy] ;

Functionally, they all seem identical: once initialized either way, they can be used regardless of how they were created. Where are the differences?

In particular, should I assume that d3/a3 are more similar to d2/a2 than d1/a1 in terms of memory pre-allocation (or lack thereof) ?

Or is this just a matter of style?


回答1:


Form one is class factory method that is an optimization useful when you know how large a collection initially needs to be or you know the size will be constant but content may change.

Form two is a class factory method equivalent to calling new. This may or may not be the same as alloc followed by init, but is effectively the same.

Form three is implicitly the same as alloc followed by initWithArray: or initWithDictionary: respectively. It's convenient but generates an unneeded immutable instance that is discarded under ARC it may not be clear when it is discarded.

Use form one or form two generally if you are not going to ever use the immutable instance again elsewhere.




回答2:


a1/d1 are allocated with enough initial space for 123 entries.

a2/d2 are allocated with enough initial space for 5 entries.

If you know that you are going to add a bunch of entries, a1/d1 are more efficient because the dictionary won't have to keep allocating more memory to hold more and more entries.

a3/d2 are closer to a2/d2 but they are really the same as:

NSMutableArray *a4 = [[NSArray array] mutableCopy];

This is less efficient than a2.




回答3:


In the first example, you not only create mutable dictionary and array, but you also specify their capacities. It's very useful if you are making some complicated calculations during which you create a lot of mutable collections, because it gives performance boost in such case. The other two examples are the same. Literals were introduced less than a year ago and they are out there just to make developers' lives easier.



来源:https://stackoverflow.com/questions/16534460/difference-between-literals-and-class-methods-for-nsmutablearray-and-nsmutabledi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!