Search code examples
cocoansmutablearraysparse-array

Is Cocoa's NSMutableArray sparse?


If I create an NSMutableArray that might have up to 2^16 elements, but will mostly be empty, will I be wasting space or is NSMutableArray implemented as a sparse array?


Solution

  • Elements in an NSArray can't be empty and there's no "default" value. To represent nil, you'd usually use the singleton [NSNull null], which is still a reference to an object so it consumes memory (the pointer). I'd consider using NSDictionary (or NSMutableDictionary) with numeric (NSNumber) keys instead.