Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Class clusters do <em>not</em> have an extra allocation and it has nothing to do with compiler magic. <s>So yes, there is a significant difference between your examples</s> (btw, -1000 internet points for dot-notation abuse.) <s>Your first example has two allocations, the second has only one.</s></p> <p>Since we don't have access to the actual source code for NSArray, we can look at GNUStep (an open source implementation) to see how they handle it. In NSArray.m (simplifying and omitting irrelevant stuff):</p> <pre><code>static GSPlaceholderArray *defaultPlaceholderArray; + (void) initialize { defaultPlaceholderArray = (GSPlaceholderArray*) NSAllocateObject(GSPlaceholderArrayClass, 0, NSDefaultMallocZone()); } + (id) alloc { return defaultPlaceholderArray; } </code></pre> <p>What's going on here is that NSArray defines a singleton, placeholder object that it always returns in <code>alloc</code>. When <code>init</code> is called on this singleton it instantiates the proper private subclass and returns that.</p> <p>So, how can we tell if Apple's Foundation is doing the same thing? Pretty easy, we just run this test:</p> <pre><code>NSArray *a1 = [NSArray alloc]; NSArray *a2 = [NSArray alloc]; NSLog(@"%p, %p", a1, a2); &gt; "0x100102f30, 0x100102f30" </code></pre> <p><code>a1</code> and <code>a2</code> do have the same memory location meaning Apple is also likely using the singleton approach. If we print out the class name it's <code>__NSPlaceholderArray</code> so that pretty much confirms it.</p> <p>So yeah, stick with <code>[NSMutableArray new]</code> :)</p> <p><strong>UPDATE:</strong> Greg Parker points out that <code>@[]</code> is also a singleton so <code>@[].mutableCopy</code> results in only one allocation. So performance-wise the two examples are the same.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload