Monday, December 9, 2013

The Foundation Collection Classes

Peter Steinberger has a good survey of the Cocoa collection classes, with some interesting performance information:

Notice that NSPointerArray requires more than 250x (!) more time than NSMutableArray. This is really surprising and unexpected. Tracking memory is harder and it’s likely that NSPointerArray is more efficient here, but since we use one shared instance for NSNull to mark empty objects, there shouldn’t be much overhead except pointers.

[…]

The eviction method of NSCache is non-deterministic and not documented. It’s not a good idea to put in super-large objects like images that might fill up your cache faster than it can evict itself. (This was the case of many memory-related crashes in PSPDFKit, where we initially used NSCache for storing pre-rendered images of pages, before switching to custom caching code based on a LRU linked list.)

Not in the article, but related, is Charles Parnot’s recent observation that the Mountain Lion release notes warn against using +[NSMapTable weakToStrongObjectsMapTable]:

However, weak-to-strong NSMapTables are not currently recommended, as the strong values for weak keys which get zero'd out do not get cleared away (and released) until/unless the map table resizes itself.

Update (2013-12-09): NSMapTable is an important building block, so it’s a mystery to me why Apple hasn’t gotten it right yet. It seems like it would be straightforward to implement clearing of the values using associated objects. Perhaps Apple is waiting until true weak-deallocation notifications are added to the runtime?

Tags: ,

1 Comment

FYI, I had a closer look at the NSMapTable behavior since that tweet, which confirms the limitation and expands it to strong-to-weak tables: http://cocoamine.net/blog/2013/12/13/nsmaptable-and-zeroing-weak-references/

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment