Deep Dive • 22 June 2026 • Written by Mansi
The Performance Cost of Existential Types in Swift
The Performance Cost of Existential Types in Swift
Swift 5.6 introduced the any keyword for existential types, making the distinction between protocols-as-types and generics explicit. While this improved readability, it also highlighted a major performance pitfall: the Existential Container.
The Hook: The Hidden Allocation
When you pass a value as any Shape, Swift doesn’t know the size of the underlying type. To handle this, it creates an Existential Container—a 5-word structure that involves a Witness Table for method lookups and potentially a Heap Allocation if the value is larger than 3 words.
The “Why”: Static vs. Dynamic Dispatch
Generics (some Shape or <T: Shape>) allow the compiler to “specialize” the code, replacing the protocol calls with direct method calls (static dispatch). Existentials (any Shape) force the compiler to look up the method at runtime, which prevents inlining and other crucial optimizations.
The Implementation: Preferring Generics
A senior developer should always default to some (Opaque Types) unless the flexibility of a heterogeneous collection (an array of different types conforming to the same protocol) is strictly required.
// ❌ SLOW: Uses Existential Containers and Dynamic Dispatch
func processShapes(_ shapes: [any Shape]) {
for shape in shapes {
shape.draw() // Witness table lookup on every iteration
}
}
// ✅ FAST: Uses Generics and Static Dispatch (Inlining possible)
func drawShape<T: Shape>(_ shape: T) {
shape.draw()
}
// ✅ MODERN: Using 'some' for Opaque Types
func renderUI(content: some View) {
// Compiler knows exactly what 'content' is at build time
}
The Verdict: Optimization Priority
- Pros of ‘any’: Allows mixing different types in one collection.
- Pros of ‘some’: Zero runtime overhead; enables compiler optimizations.
- When to use ‘any’: Only when you need a collection like
[any PaymentMethod]where elements can be different structs/classes.
Internal Connectivity
- Foundation: Roadmap Stage 2: Mastering Swift
- Next Step: Building Predictable State Machines with Swift Macros