Objective-C Category Performance

2019-06-24 03:11发布

问题:

If I used categories to break up the implementation of my Objective-C class into multiple @implementation blocks, would that make the resulting binary of my iOS app larger or affect performance at all?

Apparently, you can't Obtain details of categories on a class at runtime?. So, shouldn't the resulting binary be identical with or without categories, assuming all else equal?

Background

I have a custom subclass of UIViewController that's getting rather complex.

iOS Developer Library : Programming with Objective-C : Categories

As well as just adding methods to existing classes, you can also use categories to split the implementation of a complex class across multiple source code files. You might, for example, put the drawing code for a custom user interface element in a separate file to the rest of the implementation if the geometrical calculations, colors, and gradients, etc, are particularly complicated.

The other nice thing about categories (as compared to #pragma marks, for example) is that Xcode lets you code fold an entire @implementation block (but not the code between two #pragma mark's). This is useful if you want to keep categories (optionally folded) in the same file as the main class.

回答1:

The linker merges classes and categories when possible. If your class and its categories are all linked into the same executable at build time then the cost is zero.



回答2:

well categories are loaded dynamically and then 'combined' with the original class. This dynamic loading incurred a little overhead of course but once it is done, method calls to it don't incur any further overhead



回答3:

If the compiler is anything like c++ then it probably just adds the new functions to the class's virtual method table. I will state that I am making an assumption; however it seems logical since the compiler strictly forbid you from adding instance variables. As far as code organization I think you should be fine according to the documentation linked below:

http://objc.toodarkpark.net/moreobjc.html#756 : section "How Catergories are used"