Search code examples
cocoamacosnsarraynsdictionary

Memory footprint of NSDictionary and NSArray


The project I'm working on requires me to temporarily store hundreds and sometimes thousands of entries in a buffer. The easy way is to store each entry in an NSDictionary and all the entries in an NSArray. Each NSDictionary contains about a dozen objects (NSStrings and NSNumbers). During the entire operation, the NSArray with its dictionaries remains in memory hence my question.

Is this an expensive operation in terms of memory usage and what is a good way to test this?


Solution

  • Instruments contains a memory monitoring module. In the bottom-left corner of instruments, click on the gear icon, then choose Add Instrument > Memory Monitory. Apple's documentation should help you understand how to monitor memory with Instruments. See also this question.

    In my experience, NSDictionary and NSArray are both fairly efficient in terms of memory usage. I have written several apps that store thousands of keys/values from .csv or .xml files, and there's a fairly linear increase in memory usage as the NSDictionary is filled up. My advice is to use the Instruments profiler in some corner cases if you can built unit tests for them.

    I'm not sure I understand why you're storing the entries in both the NSDictionary and the NSArray, though.

    One thing you may want to consider if you're reaching upper bounds on memory usage is to convert the entries into a SQLite database, and then index the columns you want to do lookup on.

    EDIT: Be sure to check out this question if you want to go deep in understanding iPhone memory consumption.