Can I inline static class methods in Objective-C?
You can declare functions as inlines like this:
#ifdef DEBUG
void DPrintf(NSString *fmt,...);
#else
inline void DPrintf(NSString *fmt,...) {}
#endif
so that when you're not in DEBUG, there's no cost to the function because it's optimized and inline. What if you want to have the same thing but for a class method?
My class is declared like this:
@interface MyClass : NSObject {
}
+ (void)DPrintf:(NSString *)format, ...;
// Other methods of this class
@end
I want to convert 'DPrintf
' into something similar to the inline
so that there's n开发者_JS百科o cost to invoking the method.
But I can't do this:
inline +(void)DPrintf:(NSString *)format, ...; {}
How can I have a zero-cost static method of a class turned off for non-debug compilations?
Be careful. Objective-C methods are not the same as C functions. An Objective-C method is translated by the compiler into the objc_msgSend()
function call; you don't have control over whether a method is inline or not because that is irrelevant. You can read more about the Objective-C runtime here (Objective-C Runtime Programming Guide), here (Objective-C Runtime Reference), and here (CocoaSamurai post), and a quick Google search should bring up more info.
There is no such thing as a static method in Objective-C. There are only class methods, which are just like instance methods except they belong to a class. This means that, just like instance methods, a message send to a class must go through the message dispatch machinery to determine the correct method to call, and that is done at runtime. You could inline the call to the method dispatch machinery, but the method body still can't be inlined without a crazy level of optimization that doesn't exist in any Objective-C compiler at the moment.
At any rate, this is a micro-optimization. If profiling shows it to be necessary (which it almost never will), then you can go through the gymnastics. Otherwise, worry about the actual performance concerns in your application.
Yes!
You can accomplish this with blocks
-(void)viewDidLoad {
void(^inlineFunction)(int) = ^(int argument) {
NSLog(@"%i", argument);
};
inlineFunction(5);//logs '5'
}
Apple even documents this here (archive).
Enjoy!
精彩评论