Storing partial results into NSMutableDictionary efficiently
target_results is a NSMutableDictionary. Is this an efficient way to store partial sums into a list? Can you suggest any improvement?
NSInteger temp_key = [开发者_如何学运维rs intForColumn:@"some_int_field"];
NSInteger existing_value = [[target_results objectForKey:[NSNumber numberWithInteger:temp_key]] intValue];
if (existing_value > 0)
{
//add to existing
[target_results setObject:[NSNumber numberWithInteger:10+existing_value] forKey:[NSNumber numberWithInteger:temp_key]];
}
else
{
//new entry
[target_results setObject:[NSNumber numberWithInteger:10] forKey:[NSNumber numberWithInteger:temp_key]];
}
The most correct way to optimise is to profile and find where the actual bottlenecks are, if any. That said, working from first principles...
Firstly, there's no need to call NSNumber
twice (three times in the code, twice at runtime). Each call creates a new object, so there's a memory allocation overhead to that. So that's a cut to:
NSInteger temp_key_int = [rs intForColumn:@"some_int_field"];
NSNumber *temp_key = [NSNumber numberWithInteger:temp_key_int];
NSInteger existing_value = [[target_results objectForKey:temp_key] intValue];
if (existing_value > 0)
{
//add to existing
[target_results setObject:[NSNumber numberWithInteger:10+existing_value] forKey:temp_key];
}
else
{
//new entry
[target_results setObject:[NSNumber numberWithInteger:10] forKey:temp_key];
}
The if statement also doesn't seem to achieve anything. So you could further reduce the code to:
NSInteger temp_key_int = [rs intForColumn:@"some_int_field"];
NSNumber *temp_key = [NSNumber numberWithInteger:temp_key_int];
// will create a new entry or replace an existing entry, as per the normal behaviour
// of NSMutableDictionary
NSInteger existing_value = [[target_results objectForKey:temp_key] intValue];
[target_results setObject:[NSNumber numberWithInteger:10+existing_value] forKey:temp_key];
I seriously doubt you'll see any performance issues with that or with the original code. However, you describe your data structure as a list, so you might consider using an NSMutableArray
rather than a dictionary, assuming you can place an initialisation step.
精彩评论