What is the difference between a virtual table and a witness table?
sobes.tech AI
Answer from AI
A virtual table (vtable) is used to implement polymorphism in object-oriented programming languages, including Swift for classes. It contains pointers to class functions (methods) that can be overridden in subclasses. When a method is called through a pointer to the base class, the system looks into the object's vtable to determine which implementation of the method should be invoked (either from the base class or overridden in a subclass).
A witness table is used in Swift for protocols. It contains pointers to the implementations of protocol requirements (properties, methods, associated types) for a specific type that conforms to that protocol. When a function accepting a protocol type argument is called, the system uses the witness table associated with the passed object to access the specific implementations of the protocol requirements for that type. The witness table allows Swift to perform dynamic dispatch for protocols without the overhead associated with vtables for classes, and supports protocol flexibility.
Main differences:
| Attribute | Virtual table (vtable) | Witness table |
|---|---|---|
| Used for | Classes | Protocols |
| Contains | Pointers to class methods | Pointers to protocol requirement implementations for the type |
| Mechanism | Inheritance | Protocol conformance |
| Polymorphism | Subtype polymorphism | Protocol polymorphism |