开发者

Handler invocation speed: Objective-C vs virtual functions

I heard that calling a handler (delegate, etc.) in Objective-C can be even faster than calling a virtual function in C++. Is it really correct?开发者_Python百科 If so, how can that be?

AFAIK, virtual functions are not that slow to call. At least, this is my understanding of what happens when a virtual function is called:

  1. Obtain the pointer to vtbl.
  2. De-reference the pointer and obtain the beginning of the array of function pointers.
  3. Offset (in pointer scale) the beginning of the array with the index of the method. Considering that the index is known at compile time, it's as easy as adding a multiple of uintptr_t.
  4. Issue a call instruction.

Unfortunately, I don't know Objective-C so it's hard for me to compare performance. But at least, the mechanism of a virtual function call doesn't look that slow, right? How can something other than static function call be faster?


This is all, of course, implementation-dependent. I don't know if an Obj-C method call can be "faster" than a virtual function call, but it can certainly be in the ballpark-- there's discussion on the mechanism on SO here:

Objective C message dispatch mechanism

and Mike Ash has more here:

http://www.mikeash.com/pyblog/friday-qa-2009-03-20-objective-c-messaging.html

Bottom line is, selectors can be cached, and if the selector you're calling is cached at runtime, the dispatch is on the order of operations of a virtual function call.

Also:

  1. Standard disclaimer: The performance of this is essentially irrelevant for almost all code. It only matters in an incredible minority of cases. Can't tell from your question, but basically this should not be a decision criterion in figuring out whether to implement a bunch of code in pure Obj-C or C++.
  2. You can always watch the behavior (and count the ops :) ) explicitly by stepping through the asm in Xcode-- if you do, report back!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜