Search code examples
objective-ciosobjective-c++

NSDictionary lookups with +valueWithPointer: keys are too slow


I have an Objective C++ class, instances of which are required to store an arbitrary set of C++ objects and associate each with a corresponding Objective C object. Looking up the Objective C objects when given the C++ object is killing my performance, so I'm looking for a better solution.

I'm currently storing the pairs in an NSMutableDictionary after creating the keys using [NSValue valueWithPointer:]. The lookup time, in which +valueWithPointer: is about twice as expensive as -objectForKey:, is simply too slow.

The C++ objects are in a third-party framework, and do not provide any unique identifier.

The sets of C++ objects are always smaller than a dozen elements.

What is a faster approach to performing these lookups?


Solution

  • I see three approaches that seem worth trying:

    1. Use NSMapTable
    2. Use objc_setAssociatedObject
    3. Use std::unordered_map or std::map

    objc_setAssociatedObject uses std::unordered_map behind the scenes.