Avoid objmsg function overhead?
Can we avoid objmsg function overhead by using sel and imp means selec开发者_开发知识库tor and implementation pointer.Please tell how we can avoid it?
// first, access the SELector you're interested in (example)
SEL sel = @selector(<#SOMETHING#>);
// this is the definition of IMP
id (*IMP)(id, SEL, ...);
access the IMP for an instance of a specific class using:
+ (IMP)instanceMethodForSelector:(SEL)aSelector;
ideally, you will cast the result of instanceMethodForSelector: to an exact typedef of the function you call so the compiler can get the sig right.
once you have the object, SEL and IMP, then use the IMP as an ordinary C function pointer.
where the first message to the IMP function returned is the object(=self
), and the second argument is the selector(=_cmd
). these are the 2 hidden objc arguments.
I assume that you requirement is a result of profiling, and not a case of premature optimization.
1) You can fetch method's implementation (see Justin's answer). To elaborate - there is no much overhead in objc_msgSend
. Most of the time it will check for nil
value of self
, search for IMP in cache and perform a tail call to IMP ( http://www.friday.com/bbum/2009/12/18/objc_msgsend-part-1-the-road-map/ ). If you want to save this few instructions then ...
2) ... write your function in C from the start. It is much more readable and reliable solution.
The only serious answer to this question is
Use something other than Objective-C
Honestly, any way to avoid obj_msg_send()
is guaranteed to be fragile and will probably save you nanoseconds per call. If you do have a very short function that is called very frequently, then you should probably just use C to reimplement that function. In almost all other cases, it's not worth the bother.
精彩评论