ObjectiveC category and speed of execution and typing

I am thinking of wrapping commonly used Cocoa object selectors with my own code to improve typing speed. A typical example would be something like a white trim selector: -

[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


My options are: -

(1) wrap it in an NSSTring category like

- (NSString *)Trim 
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


(2) define it as a macro instead like so

#define TRIM(X) [X stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]


I would prefer option (1) above, but are there any performance hits?


source to share

1 answer

It is highly unlikely that the category will make any significant or even noticeable difference in performance.

The category method requires one additional post submission, so yes, it will be slower than the macro. But the ObjC message dispatcher is one of the most optimized bits of code in the entire OS - it doesn't slow down in any way.

However, if you use the macro multiple times, your code will grow in size more than it would with the category, which could have worse side effects. (But that's not a lot of code, so a lot of examples will be needed for real changes.)

So, as usual, it depends entirely on your particular situation - you will need to measure it and watch it. I would be amazed if you could measure the difference.



All Articles