Does Swift use message dispatch for methods?

swift

Solution

Sometimes yes, sometimes no. If you have pure swift code, and do not expose your classes/protocols to Objective-C with the `@objc` decoration, it appears that pure-swift method calls are not dispatched via `objc_msgSend`, however in other cases they are. If the protocol your swift object adopts is declared in Objective-C, or if the swift protocol is decorated with `@objc`, then method calls to protocol methods, even from swift objects to other swift objects, are dispatched via `objc_msgSend`.

The documentation is currently a little thin; I'm sure there are other nuances... but empirically speaking (i.e. I've tried it out) some swift method calls go through `objc_msgSend` and others don't. I think getting the best performance will be dependent on keeping your code as much pure-swift as possible and crossing the Obj-C/swift boundary as little as possible, and through bottleneck interfaces/protocols, so as to limit the number of swift calls that have to be dispatched dynamically.

I'm sure more detailed docs will emerge sooner or later.

Problem

I'm sure my terminology is off, so here's an example: - C/C++ has methods and virtual methods. Both have the opportunity to be inlined at compile time. - C#'s CIL has `call` and `callvirt` instructions (which closely resemble C++ methods and virtual methods). Although almost all method calls in C# become `callvirt` (due to langauge snafu) the JIT compiler is able to optimize most back to `call` instructions and then (if worthwhile) also inline them. - Objective-C method calls are done very differently (and inefficiently); a message object is passed via `objc_msgsend` every time you call a method, it's a form of dynamic dispatch, and can never be inlined. Reading up on the language specification for functions for Swift, I don't know if Swift is using the same messaging system as Objective-C or something different.

Original source