skip to content

Method Call Mechanisms

Swift calls a method statically, through a class vtable, a protocol witness table or Objective-C messaging. Interviewers ask which applies where and how final helps the optimizer.

on this pageshow

explore

questions

6

In Swift, how does marking a class or a method `final` change the way calls to it are dispatched, and why can that run faster?

level: juniorimportance: must knowfreq 55%

answer

  1. what the compiler can prove
  2. an indirect call through a table
  3. a direct call, then inlining
  4. stored properties are accessors too

basics

~20 s

A non-final class method is called through the class's vtable, an indirect call the compiler cannot see through. Final promises that no override exists, so the compiler calls the one implementation directly and can inline it.

solid answer

~50 s

By default a method or property of a Swift class can be overridden, so a call such as `engine.mix(x)` loads the object's class metadata, reads the method's slot in the **vtable** and jumps to whatever function sits there. Marking the method `final`, or the whole class `final`, tells the compiler that no subclass can replace it, so it emits a **direct call** to the single implementation. The indirect jump is cheap; the larger win is that a direct call can be **inlined**, and inlining opens the code to the optimizations that follow it. The same holds for stored properties: a non-final one may be overridden by a computed property, so it is read through its getter's vtable slot, while a `final` one is a plain field access. Structs and enums never had a vtable, and `final` changes nothing about allocation or reference counting.

code

swift · 16 lines
swift
class AudioEngine {
  func mix(_ sample: Int) -> Int { sample * 2 }
  final func clamp(_ sample: Int) -> Int { min(sample, 255) }
}

final class Equalizer {
  func boost(_ sample: Int) -> Int { sample + 10 }
}

func process(_ engine: AudioEngine, _ eq: Equalizer, _ sample: Int) -> Int {
  let mixed = engine.mix(sample)      // vtable lookup: a subclass may override mix
  let clamped = engine.clamp(mixed)   // direct call: clamp is final
  return eq.boost(clamped)            // direct call: Equalizer is a final class
}

print(process(AudioEngine(), Equalizer(), 100))   // prints 210

go deeper

for a junior

Recall that class members are overridable by default and so called through a vtable, while final members, final classes, structs and enums get direct calls. Say final is a promise the compiler exploits.

for a middle

Explain the vtable slot load and indirect jump, why it blocks inlining, and how private, fileprivate and whole-module optimization let the compiler infer final without the keyword.

for a senior

Mark classes final by default where no subclass is designed, read optimized SIL or a profile before claiming a win, and know a genuinely polymorphic call site stays dynamic whatever you mark.

for a principal

Treat final as a design statement as much as a hint: inside a module it documents that no subclass is intended, while across modules open is the real commitment, since a public class is already closed to other modules.

## What a class method call has to decide A Swift class is open to **subclassing** inside its module, and its methods, properties and subscripts can be **overridden** unless something says otherwise. That means a call written as `engine.mix(sample)` does not name one function: it names whichever implementation the object's actual class provides. The compiler, looking only at the static type `AudioEngine`, often cannot tell whether the object is an `AudioEngine` or some subclass that overrides `mix`. Swift answers that question at run time with a **vtable** (virtual method table): a per-class table of function pointers, one slot per overridable member. A subclass inherits the table and replaces the slots it overrides. ## The vtable call, step by step In the unoptimized code the Swift 6.4 compiler emits for a non-final method, the call does three things: 1. Load the class metadata pointer stored at the start of the object. 2. Load the function pointer from the method's fixed slot in that metadata. 3. Make an **indirect call** through that pointer, passing the object as `self`. In the compiler's intermediate language (SIL) this appears as a `class_method` instruction. The loads are cheap, but Swift's own optimization guide notes that dynamic dispatch is slower than a direct call "because it prevents many compiler optimizations in addition to the overhead of performing the indirect call itself". The optimizer cannot **inline** a function it cannot identify, so it cannot fold constants across the call, adapt the body to the caller's arguments or remove work whose result the caller never uses. ## What `final` lets the compiler do `final` is a promise checked at compile time: no subclass may override this member (on a member), or no subclass may exist at all (on a class). Once the promise holds, the compiler knows the exact implementation, so it emits a **direct call** (`function_ref` in SIL) and is free to inline it. | Declaration | How a call is dispatched | |---|---| | `func` in a non-final class | vtable, unless the optimizer proves no override exists | | `final func` in any class | direct | | any method of a `final class` | direct | | `static func` in a class | direct (`static` means `class final` there) | | method of a struct or enum | direct | The same reasoning covers **stored properties**. A subclass may override a non-final stored property with a computed one, so reading `mixer.volume` calls its getter through the vtable. A `final var` is read as a direct field access. ## What `final` does not do - It does not change **allocation**: instances of a final class are allocated and freed exactly like any other class instances. - It does not skip **ARC**: strong references to a final class are retained and released as before. - It does not **force** inlining; it only makes inlining possible. The optimizer still weighs code size. - It does not make calls through a base class direct: marking a subclass `final` changes nothing for a call whose static type is the overridable base class. - It has no meaning for **structs and enums**, which cannot be subclassed and are dispatched directly already. ## Inference without the keyword The compiler can sometimes infer `final` on its own. A `private` or `fileprivate` member can only be overridden inside its file, so the compiler checks that file. With **whole-module optimization**, it sees every file of the module and can infer `final` for internal members nothing overrides. An `open` member never gets this inference, because another module may subclass it. Writing `final` yourself works in every build mode, documents the design, and turns an accidental override into a compile error. ## Seeing it for yourself Compile a file with `xcrun swiftc -O -emit-sil Engine.swift` and search the output for `class_method`: every hit is a call that still goes through a vtable. A `final` member shows up as a `function_ref` or, more often, as no call at all because its body was inlined. ## When it pays off The dispatch cost is real but small per call, so it shows up only in particular places: - **Hot loops with small bodies**, such as a getter or a one-line computation called millions of times, where the call overhead and the lost inlining are a large share of the work. - **Property access in tight code**, because a read of a non-final property is, unless devirtualized, a call rather than a load. - **Library types** whose methods clients call often: other modules cannot see your internal subclasses, so only an explicit `final` lets them call directly. Elsewhere the benefit is mostly clarity. A common team habit is to declare classes `final` unless subclassing is part of the design, then measure an optimized build before claiming any speed-up from it.

  • If a Swift class has no subclasses at all, does the compiler still use the vtable for its non-final methods?
    It depends on what the compiler can see. Compiling file by file, an internal method might be overridden in another file, so calls stay vtable calls. `private` and `fileprivate` members can be checked within their file. With whole-module optimization the compiler sees every file and can infer `final` for internal methods nothing overrides. An `open` method never gets that inference.
  • Does marking a Swift class `final` make its instances cheaper to allocate or to retain?
    No. `final` changes dispatch only. Instances are allocated and freed the same way, and strong references are retained and released as before. What changes is that calls and property accesses become direct, which may let inlining remove redundant work around the call, but allocation and reference counting follow the usual class rules.
  • Why is reading a non-final stored property of a Swift class a dynamic call?
    A subclass may override a stored property with a computed property or add observers, so the compiler cannot assume a plain field read. It calls the property's getter through the vtable instead. Marking the property `final`, or the class `final`, lets the compiler read the field directly.

A non-final method is like 'whoever is on call tonight': you must check the rota every time before phoning. A final method is a named colleague, so you can dial directly and even prepare their answer in advance, which is what inlining does.

  • final only stops subclassing; calls still go through the vtable afterwards
  • Every Swift method call is a runtime lookup by name, like an Objective-C message
  • Struct methods need final before the compiler can call them directly
  • Marking a class final makes its instances live on the stack
  • The only cost of a vtable call is two extra memory loads
open as a page

In Swift, which dispatch mechanism handles a call to a struct method, an overridable class method, a protocol requirement and an `@objc dynamic` method?

level: middleimportance: must knowfreq 65%

basics

~20 s

Swift picks per call site: struct, enum and final methods are direct calls; overridable class methods use the class vtable; protocol requirements called on a generic or existential value use a witness table; @objc dynamic members use objc_msgSend.

open as a page

In Swift, how is a method declared in a class extension dispatched, and why can't a subclass override it unless it is `@objc`?

level: middleimportance: should knowfreq 30%

basics

~20 s

A method declared in a class extension gets no vtable slot, so Swift calls it directly, as if final, and rejects an override. Marked @objc on Apple platforms, it is dispatched by Objective-C message instead, which an override can replace.

open as a page

Without writing `final`, how do `private`, `fileprivate` and whole-module optimization let the Swift compiler call class methods directly?

level: middleimportance: should knowfreq 40%

basics

~20 s

The compiler can call a class method directly once it sees every possible override. Private and fileprivate members limit that search to one file; whole-module optimization widens it to the module, covering internal and non-open public members.

open as a page

A Swift method swizzled with `method_exchangeImplementations` changes for Objective-C callers but not for Swift callers; why, and what does `dynamic` change?

level: seniorimportance: should knowfreq 30%

basics

~20 s

For a class-body method, @objc only adds an Objective-C entry point; Swift callers still use the vtable or a direct call, so swizzling that entry misses them. @objc dynamic makes every access, Swift's included, a message the runtime can redirect.

open as a page

A Swift render loop calls `draw()` on shapes held as a class hierarchy, as `[any Shape]` and through a generic function; where does each call's dispatch cost come from, and how do you remove it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Class elements dispatch through the vtable and [any Shape] elements through each value's witness table, because the type varies per element; a specialized generic over one type calls directly. An enum over a closed set of shapes gives direct, inlinable calls.

open as a page