Why mark something final in Swift except for architectural considerations?

前端 未结 1 1031
春和景丽
春和景丽 2021-01-14 06:10

Except for obvious reasons, such as if by design I do not want certain method, or property, or whatever to be overridden down the inheritance tree, are there other reasons t

相关标签:
1条回答
  • 2021-01-14 06:36

    From Apple's Swift blog: Increasing Performance by Reducing Dynamic Dispatch

    Swift allows a class to override methods and properties declared in its superclasses. This means that the program has to determine at runtime which method or property is being referred to and then perform an indirect call or indirect access. This technique, called dynamic dispatch, increases language expressivity at the cost of a constant amount of runtime overhead for each indirect usage.

    Using final is one of several ways to improve performance by eliminating such dynamism:

    The "final" keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. This allows the compiler to safely elide dynamic dispatch indirection.

    0 讨论(0)
提交回复
热议问题