Does adding a method to an Objective-C class as a category have any effect on that class's memory usage?
The impact of a category on the class
The Objective-C runtime ultimately honors your category methods by producing a class hierarchy for your instance which includes the category. The instances of a class implementing a category won't be more expensive or demanding of memory than an additional subclass would have been. Category methods are applied at runtime, but once the method is added to the class, it will be no different from the methods defined on that class. The machinery for message sending between these objects will all be the same.
Categories are more about code design and separation of concerns. You can simply use them in step with established Cocoa patterns as a tool to help you design your classes, rather than thinking in terms of memory optimizations.
The overall impact of categories on the runtime environment
@NSResponder reminds me of a further good point. Because categories are loaded at run-time, they won't be loaded until they are used. A really large class or a class cluster might include code for higher level frameworks in a separate category. If you avoid the higher-level framework altogether, you'll never have to load the categories it adds. For example, a class may work fine in a Foundation layer, and then load extra functionality when it's used from a Cocoa layer. So this can be thought of as saving space, and that's a good answer for the picture at large.
Still, if you are simply writing some classes, this shouldn't be your primary means for optimizing memory yourself. Unless you are writing a large body of code which spans multiple layers, you are typically declaring categories in order to make use of them yourself or to make them available for some other object to use. Objective-C and the Cocoa frameworks have good machinery for lazily loading bundles of code, which serves this purpose well.
The benefit of categories for memory footprint is that the app won't load a category until you use it. The canonical example of this back in the NeXTSTEP days was to put a view's printing code in a category.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With