2 Answers

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.

The answer was excellent, but I got confused on this part: "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." Could you please explain. that?

If you were to call the makeNoise method on an instance, the compiler would have to figure out which makeNoise method you are referring to. They both have the same name but different implementations. The compiler has to do more work to figure this out.

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.

Posting to the forum is only allowed for members with active accounts.
Please sign in or sign up to post.