Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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.

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top