Skip to content

Instantly share code, notes, and snippets.

@Pegolon
Created January 28, 2016 11:36
Show Gist options
  • Select an option

  • Save Pegolon/7a4bae82d36016d280b4 to your computer and use it in GitHub Desktop.

Select an option

Save Pegolon/7a4bae82d36016d280b4 to your computer and use it in GitHub Desktop.
Performance of NSDictionary initialization
- (void)test_stepByStep_withCapacity
{
NSMutableArray *keys = [NSMutableArray new];
NSMutableArray *values = [NSMutableArray new];
srand(0x21112005);
int entryCount = 1000000;
for (int ix = 0, ixMax = entryCount; ix < ixMax ; ix++) {
NSString *key = [NSString stringWithFormat:@"Key#%d", (ix + 1)];
NSString *value = [NSString stringWithFormat:@"Value with %d", rand()];
[keys addObject:key];
[values addObject:value];
}
// Step-by-step with initial capacity (0.411 sec)
[self measureBlock:^{
NSMutableDictionary *stepByStep = [NSMutableDictionary dictionaryWithCapacity:entryCount];
[keys enumerateObjectsUsingBlock:^(NSString * _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
stepByStep[key] = values[idx];
}];
IfoDebug(@"Dictionary has %d entries", stepByStep.count);
}];
}
- (void)test_stepByStep_noInitialCapacity
{
NSMutableArray *keys = [NSMutableArray new];
NSMutableArray *values = [NSMutableArray new];
srand(0x21112005);
int entryCount = 1000000;
for (int ix = 0, ixMax = entryCount; ix < ixMax ; ix++) {
NSString *key = [NSString stringWithFormat:@"Key#%d", (ix + 1)];
NSString *value = [NSString stringWithFormat:@"Value with %d", rand()];
[keys addObject:key];
[values addObject:value];
}
// Step-by-step without initial capacity (0.788 sec)
[self measureBlock:^{
NSMutableDictionary *stepByStep = [NSMutableDictionary new];
[keys enumerateObjectsUsingBlock:^(NSString * _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
stepByStep[key] = values[idx];
}];
IfoDebug(@"Dictionary has %d entries", stepByStep.count);
}];
}
- (void)test_atOnce
{
NSMutableArray *keys = [NSMutableArray new];
NSMutableArray *values = [NSMutableArray new];
srand(0x21112005);
int entryCount = 1000000;
for (int ix = 0, ixMax = entryCount; ix < ixMax ; ix++) {
NSString *key = [NSString stringWithFormat:@"Key#%d", (ix + 1)];
NSString *value = [NSString stringWithFormat:@"Value with %d", rand()];
[keys addObject:key];
[values addObject:value];
}
// At once (0.271 sec)
[self measureBlock:^{
NSDictionary *atOnce = [NSDictionary dictionaryWithObjects:values forKeys:keys];
IfoDebug(@"Dictionary has %d entries", atOnce.count);
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment