Egor Bedunkevich643 Points
Static and dynamic dispatch
I'm reading an article about static and dynamic dispatch. I don't get it. Can someone please explain it to me?
Steven Deutsch21,044 Points
Hey Egor Bedunkevich,
When something is dynamically dispatched, this means the compiler does not know which method is being called at runtime and has to figure it out. The reason for this is because Swift allows you to override the methods or properties of a superclass in one of its subclasses. Therefore, the compiler needs to determine are you referring to the superclasses' implementation or are you referring to the implementation of the subclass? This can increase the overhead of your application.
When something is statically dispatched, we are dealing with the opposite scenario. With static dispatch, the compiler does in fact know which property or method is being called at runtime, which is a performance boost. You can achieve static dispatch by marking a base class with the "final" keyword. This lets the compiler know that this class can not have any subclasses and that the method/property you are referring to is its only implementation.
Another example is the "static" keyword for when defining type methods or properties. This keyword is really just short for "final class". This lets the compiler know that this is the final implementation of this method and it will not be overridden. Therefore, it will be statically dispatched.
When defining a type method you can mark it with "class" or "static", but which you choose determine how it will be dispatched.
Hope this clears a few things up, Good Luck!
Cindy LeaPro Student 6,482 Points
After doing some reading, I found this to be a good answer from bytes.com:
The static and dynamic means the time to dispatch. The static dispatch be determined at compile time, dynamic at runtime. In C++ dynamic dispatch is implemented by using virtual function (or pointer to function as c style).
Hope that helps.