简体   繁体   中英

What is the default capacity of NSMutableDictionary?

Basically when you call

[[NSMutableDictionary alloc] init];

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM