I'm sure my terminology is off, so here's an example:
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.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.
Method Dispatch is how a program selects which instructions to execute when invoking a method. It's something that happens every time a method is called, and not something that you tend to think a lot about.
Since struct and enum are value types and does not support inheritance, the compiler puts it under Static dispatch as it is aware of the fact that it can never be subclassed.
Dispatch Methods are the load balancing algorithms that determine how client requests are distributed between servers in a farm. AppDirector receives requests for service from clients and decides to which server to direct each request.
Static and Dynamic are the two forward facing dispatch techniques. Static dispatch is used in situations where inheritance isn't allowed and the compiler can only call one method. Dynamic dispatch is used in protocol required methods, inheritance in classes and class type methods.
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.
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