Allegro Dec 1, 2014

Swift Method Dispatching Mechanisms

Article Summary

Ever wonder why Swift is faster than Objective-C? The answer lies in how it dispatches method calls, and the difference is more dramatic than you might think.

This deep dive from a Swift Warsaw presentation breaks down Swift's method dispatching mechanisms at the assembly level. The author walks through Virtual Method Tables (vtables), comparing them to Objective-C's runtime message passing to reveal exactly what makes Swift performant.

Key Takeaways

Critical Insight

Swift's vtable dispatch replaces Objective-C's runtime message passing with compile-time offset calculations, trading dynamism for speed and battery efficiency.

The article includes actual SIL and assembly code showing how a simple kung fu test method compiles down to just a handful of processor instructions.

About This Article

Problem

Swift developers needed to understand how method dispatching works at runtime. The key question was how virtual method tables, or vtables, are structured in memory. Instead of dictionary-style lookups, Swift uses offset-based lookups to find methods.

Solution

Kamil Borzym used swiftc --emit-sil and swiftc -S to dig into Swift's compilation process. By examining the SIL intermediate code and assembly output, he found that metadata pointers store function implementations at fixed byte offsets like 0x48, 0x50, and 0x58. This is how vtable dispatch actually works.

Impact

Swift's vtable dispatch is faster than Objective-C's approach. Objective-C's objc_msgSend has to scan the inheritance tree to find methods. Swift skips that step entirely. Instead, it uses direct offset-based calls that become simple pointer arithmetic and function jumps in assembly code.

Recent from Allegro

Related Articles