Dispatch techniques: Dynamic dispatch and Static Dispatch
4 types of dispatch techniques —
- Inline (Fastest)
- Static Dispatch
- Virtual Dispatch
- 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
dynamickeyword and we need to prefix it with@objckeyword so as to expose our method to Objective-C runtime
Static Dispatch is supported by both value types and reference types.
With this dispatch technique, the compiler knows, at compile-time, 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
finalandstaticas both of them ensures that the class and method cannot be overridden
Comments
Post a Comment