Search code examples
iosobjective-cobjective-c-runtime

Dispatch via vtable is faster than a hash table, but would consume tremendous amounts of memory if used everywhere


I can't understand it "Dispatch via vtable is faster than a hash table, but would consume tremendous amounts of memory if used everywhere." which is in this blog objc_explain_objc_msgSend_vtable


Solution

  • Obj-C is not C++.

    In C++, each class has a known (at compile time) set of virtual functions, which is typically significantly smaller than the complete set of functions defined for that class and all of its subclasses. (In C++ you must explicitly mark which functions are virtual, and by default they are not.)

    In Obj-C every method is "virtual" (in C++ speak), the selector list is variable, methods can be redefined at runtime (added and replaced), and the list is indefinite (technically, you can send any object any message, even one it doesn't respond do it).

    So in C++ it is pretty trivial to build a linear array of every virtual function an object will need to dispatch, assign an offset into that array for each function, and compile that into the code.

    If you wanted to use virtual dispatch tables in Obj-C you'd have to create an array for every class that contained every possible selector. For even modest programs, each list would be huge, and it would grow exponentially with project complexity. I mean, every class would have its own array of (what?) 20,000 different selectors, and there are thousands of classes...

    A hash table, on the other hand, contains a variable set of method function pointers defined for that class. The set is typically just the subset of the selectors that have actually been sent to those objects, so it is much (much) smaller than the complete set of selectors you could potentially send to an object of that class. This makes the hash table of methods efficient and self-optimizing, even if dispatching take a little longer.