Dispatch techniques: Dynamic dispatch and Static Dispatch


4 types of dispatch techniques —

  1. Inline (Fastest)
  2. Static Dispatch
  3. Virtual Dispatch
  4. Dynamic Dispatch (Slowest)

Dynamic dispatch

Swift allows a class to override methods and properties declared in its superclasses. ... This technique, called dynamic dispatch, increases language expressivity at the cost of a constant amount of runtime overhead for each indirect usage.

Method Dispatch is the mechanism that helps to decide which operation should be executed, or more specifically, which method implementation should be used.

Dynamic Dispatch is supported only by reference types(i.e. Class). The reason for this is that, for dynamism, or dynamic dispatch, in short, we need inheritance and our value types do not support inheritance.

  • To achieve Dynamic Dispatch, we use inheritance, subclass a base class and then override an existing method of the base class. Also, we can make use of dynamic keyword and we need to prefix it with @objc keyword so as to expose our method to Objective-C runtime


Static Dispatch

Static Dispatch is supported by both value types and reference types.

With this dispatch technique, the compiler knows, , which method implementation is to be called for a method. Thus the compiler can perform certain optimizations and can even convert the code to Inline, if possible, thus making the overall execution speed insanely fast!

  • To achieve Static Dispatch, we need to make use of final and static as both of them ensures that the class and method cannot be overridden

Comments