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 no 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?
By declaring a function inline you tell the compiler to replace the complete code of that function directly into the place from where it was called.
The static keyword is usually used to define global objects or functions that are only visible in the file where they are defined.
In C, static means the function or variable you define can be only used in this file(i.e. the compile unit) So, static inline means the inline function which can be used in this file only.
An inline definition is a function defined with the keyword inline, without either the keywords static or extern, and with all prototypes appearing within the source (or included files) also containing the keyword inline without either the keywords static or extern.
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.
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