Performance penalty using respondsToSelector

2.5k Views Asked by At

I will be refactoring a lot of old code to make the client more robust to bad server responses and log exceptions whenever the JSON response has invalid values, and I am thinking of checking the validity (data type) for each node being parsed using respondsToSelector.

I am checking for a data type (int, bool etc) in the response

[[json objectForKey: @"feature_enabled"] boolValue], 

which crashes the app if the @"feature_enabled" node has anything other than 0 or 1

to get around this issue, here's how I'd do it

if ([[json objectForKey: @"feature_enabled"] respondsToSelector: @selector(boolValue)]){
          BOOL featureEnabled = [[json objectForKey: @"feature_enabled"] boolValue];
}else{
          Log Exception
}

I haven't done any kind of performance analysis on this code, but I'd like to know if anyone can suggest what kind if performance penalty I should expect if I am going to check responds to selector for every JSON response I intend to parse.

Any pointers to the sources of info appreciated!

2

There are 2 best solutions below

4
On BEST ANSWER

You may want to consider using isKindOfClass which I believe is the best performance:

if([[yourDictionary objectForKey:@"yourKey"] isKindOfClass:[NSArray class]]) { //assume its an array and handle it }

3
On

respondsToSelector: checks for nil. It not nill, it calls IMP lookUpMethod(Class cls, SEL sel, BOOL initialize, BOOL cache, id inst) that returns the methods from the IMP cache (using the CacheLookup macro). If not found, it tries to fill the cache looking up the method in the class itself, which involves repeating the operation on the superclasses. If that fails, it runs the forwarding mechanism.

isKindOfClass: compares the isa pointers of both classes. If that fails, it repeats with the superclass, which is just the field 'super_class' in the struct objc_class.

So the proper way to distinguish between two objects is isKindOfClass:.

Note that processing your JSON data will be gazillion times slower than everything above. Not finding a selector doesn't bring the system to a halt or anything.