I have a dictionary that stores an object using a combination of the class name and selector as the key. I’m using the following function in order to calculate the hash:
+(NSString*) getKeyForClass:(Class) clazz andSelector:(SEL) selector {
return [NSString stringWithFormat:@"%@_%@",NSStringFromClass(clazz), NSStringFromSelector(selector)];
}
While running a profiler i’ve discovered that this function is the bottleneck of the computation. Is there a better (= more efficient) way to create a key from a class and a selector?
A few alternatives.
Keep using a string as a key, but do it faster:
Using a string is a bit more heavyweight than you really need, but it is at least simple.
Using
-[NSString stringByAppendingString]would be faster. Parsing format strings is a lot of work.It may be better to use a single
NSMutableStringinstead of making intermediate strings. Profile it and see.Use a custom object as a key:
You can make a custom object as the key that refers to the class and selector. Implement
NSCopyingand-isEqual:and-hashon it, so you can use it as a key in a dictionary.Eliminate the middleman:
If you never need to pull the class and selector out of your key object, then you can just use the hash as computed above, stored in an
NSNumber.