3

I'm doing some app optimizations and in big loops the checks on NSMutableDictionary's are fairly taxing:

if ([self.variantBufferSequence objectForKey:[variant valueForKey:@"model_no"]] == nil) {
    [self.variantBufferSequence setObject:[NSMutableDictionary new] forKey:[variant valueForKey:@"model_no"]];
}

Is there a lighter way to check the existence of the entry (objectForKey) in the if-statement?

  • 1
    Did you check if most time is spent in `objectForKey`? – Willeke Mar 26 '16 at 11:58
  • 2
    Why do you think the `objectForKey:` call is expensive rather than the `valueForKey` call (which is generally the slower of the two, and can be extremely slow). What is `variant`? Is this test likely to be true often? What did Instruments say when you profiled this? Optimizing one line of code in isolation is seldom the right approach; what value is changing in the loop? How large is this dictionary? – Rob Napier Mar 26 '16 at 14:25

1 Answers1

2

In the last versions of objc and clang, you can check existence of a key in a dictionary with a more compact notation.

This little example works for me:

NSMutableDictionary *description = @{@"model_no":@"key1"}.mutableCopy;
NSMutableDictionary *dictionary = @{@"key1":@"value1"}.mutableCopy;

if(dictionary[description[@"model_no"]]){
    NSLog(@"It exists!");
} else {
    NSLog(@"It doesn't exists!");
}

Try to replace key1 with key2 in description.

Reference

Community
  • 1
  • 1
Nicola Giancecchi
  • 3,045
  • 2
  • 25
  • 41
  • In my tests, `objectForKey:` is slightly faster than subscripting (I suspect that `objectForKeyedSubscript:` is implemented as a call to `objectForKey:`). I wouldn't expect it to matter much either way, but is there any reason you believe this approach is faster than the OP's code? (Ignoring the removal of `valueForKey:`, which only works if `variant` is a dictionary.) – Rob Napier Mar 26 '16 at 14:54
  • This gave me a very minor speed improvement. `variant` is indeed a mutable dictionary with around 20 small values. I tested it repeatedly with the Time Profiler and got about 5% gain. I hoped for something more spectacular, but not complain :) –  Mar 27 '16 at 15:35