3

Basically when you call

[[NSMutableDictionary alloc] init];

Apple will create a dictionary of some default size. What is that default size?

14wml
  • 4,048
  • 11
  • 49
  • 97
  • That's an implementation detail that shouldn't matter. Are you just curious or do you have a specific concern? – rmaddy Jul 13 '17 at 23:23
  • @rmaddy I'd just like to know please – 14wml Jul 13 '17 at 23:25
  • @rmaddy And I'm not sure where to find this information – 14wml Jul 13 '17 at 23:25
  • You might be able to find out by using https://stackoverflow.com/questions/15475924/how-to-calculate-total-size-of-nsdictionary-object and comparing the size of a default NSMutableDictionary to one where you used initWithCapacity: – user3486184 Jul 13 '17 at 23:29
  • @user3486184 would you mind writing out the code how to do that? – 14wml Jul 13 '17 at 23:45
  • I think the size varies based on the chipset. But you can always check the size of object created by malloc_size(). – GeneCode Jul 14 '17 at 03:10
  • The code I was looking at iterates over the elements of the NSMutableDictionary - it won't report differences in initial sizes, I'm afraid. – user3486184 Jul 26 '17 at 17:36

1 Answers1

1

Interestingly, on iOS at least it appears that Apple does the same thing for init as if it were initWithCapacity:0. I ran the following code under Instruments:

int max=1000000;
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:max];
for(int i=0; i < max; i++) {
    [array addObject:[[NSMutableDictionary alloc] init]];
}
if(true) return array;  // Don't let the compiler remove the ref

Next I did something very similar but with 0 capacity explicitly specified:

int max=1000000;
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:max];
for(int i=0; i < max; i++) {
    [array addObject:[[NSMutableDictionary alloc] initWithCapacity:0]];
}
if(true) return array; // Don't let the compiler remove the ref

Both of these ran with a max consumption of 55.3 MB on my iOS 9 device. Then I tried using initWithCapacity:1 when creating the dictionaries:

int max=1000000;
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:max];
for(int i=0; i < max; i++) {
    [array addObject:[[NSMutableDictionary alloc] initWithCapacity:1]];
}
if(true) return array; // Don't let the compiler remove the ref

In that case my max consumption was 116.4 MB.

As other commenters have noted, this may vary from OS to OS and even from version to version. Don't rely on it, but that's one way to tell what NSMutableDictionary init is doing.

user3486184
  • 2,147
  • 3
  • 26
  • 28