# 动态分派

**动态分派**（Dynamic dispatch）是指在运行时，根据接收调用的对象的实际类型——而非源代码中可见的类型——来选择执行多态操作的哪一个实现。用 C++ 的话说，[虚函数](https://www.edgepedia.org/zh/virtual-function)调用的解释取决于被调用对象的动态类型，而非虚成员函数调用的解释则只取决于指代该对象的指针或引用的静态类型<sup>[1](https://timsong-cpp.github.io/cppwp/std17/class.virtual)</sup>。

| 关键事实 | 细节 |
|---|---|
| 定义规则 | 虚调用按对象的动态类型解析；非虚调用按指针或引用的静态类型解析<sup>[1](https://timsong-cpp.github.io/cppwp/std17/class.virtual)</sup> |
| 标准机制 | 常见实现使用虚表（vtable），即一张用于分派虚函数、访问虚基类子对象并支持 RTTI 的表<sup>[2](https://refspecs.linuxfoundation.org/cxxabi-1.83.html)</sup> |
| 每对象开销 | 在常见的虚表实现中，每个多态对象通常带有一个隐藏的虚表指针（64 位 Itanium 上为 8 字节）<sup>[3](https://www.learncpp.com/cpp-tutorial/the-virtual-table/)</sup><sup> • </sup><sup>[4](https://notes.camadkins.com/cs/languages/common/dispatch-vtables-fat-pointers-and-dictionaries)</sup> |
| 每次调用开销 | 在常见的虚表实现中，为两次内存加载加一次间接跳转，与继承深度无关，为 O(1)；缓存命中时约 2–5 个周期，在一项现代基准测试中比直接调用多约 1.42 纳秒<sup>[5](https://cpp.wyattau.com/object_oriented/2_runtime_polymorphism/1_vtables/)</sup><sup> • </sup><sup>[6](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)</sup> |
| 实测占比 | C++ 程序花在分派代码上的执行时间占比中位数为 5.2%（最高 47%）；若所有函数均为虚函数，中位数为 13.7%<sup>[7](https://dl.acm.org/doi/10.1145/236338.236369)</sup> |
| 出现频率 | 在 SPEC JVM98 中，Java 虚方法调用每 12 到 40 个字节码出现一次<sup>[8](https://static.usenix.org/event/jvm02/full_papers/zendra/zendra_html/index.html)</sup> |
| 主要缓解手段 | 去虚化与内联缓存，在类型可预测时把动态调用转换为可直接内联的调用<sup>[5](https://cpp.wyattau.com/object_oriented/2_runtime_polymorphism/1_vtables/)</sup><sup> • </sup><sup>[8](https://static.usenix.org/event/jvm02/full_papers/zendra/zendra_html/index.html)</sup> |

## 静态分派与动态分派

分派可以发生在两个不同的时刻。Rust 那样的单态化泛型会把调用编译成直接调用<sup>[4](https://notes.camadkins.com/cs/languages/common/dispatch-vtables-fat-pointers-and-dictionaries)</sup>。动态分派则把选择推迟到运行时，查询对象的实际类型。

这一区分与参数个数无关。C++ 和 Java 是动态单分派语言，其编译器在选择重载时会考虑所有参数的静态类型，文献中称这种组合为静态多分派；[Smalltalk](https://www.edgepedia.org/zh/smalltalk) 是单分派语言，而 CLOS 和 Cecil 是多分派语言，依据多个参数的运行时类型进行选择<sup>[9](http://webdocs.cs.ualberta.ca/~paullu/Papers/COOTS2001-HTML/mdj.html)</sup>。就其完整形式而言，多分派通过考察一次调用中多个参数的运行时类型来选择要执行的方法体，而大多数面向对象语言仍然只提供单分派<sup>[10](https://psycnet.apa.org/doi/10.1145/1449764.1449808)</sup>。

Python 和 [JavaScript](https://www.edgepedia.org/zh/javascript) 这类鸭子类型的动态语言不把分派绑定在类层次结构上<sup>[11](https://www.cl.cam.ac.uk/teaching/1718/L25/5DynamicDispatchandDuckTyping.pdf)</sup>。

## 实现机制

**虚表逐步解析。** C++ 标准并未规定虚函数如何实现；各实现通常使用虚表，即在编译期建立的一个静态数组，每个虚函数对应一个函数指针条目<sup>[3](https://www.learncpp.com/cpp-tutorial/the-virtual-table/)</sup>。使用虚表的实现通常会给多态对象添加一个隐藏的 `*__vptr` 指针；它指向一张虚表，需要指针大小的存储空间<sup>[3](https://www.learncpp.com/cpp-tutorial/the-virtual-table/)</sup>。某个特定最终派生类的所有对象，其虚表指针都指向同一组虚表<sup>[2](https://refspecs.linuxfoundation.org/cxxabi-1.83.html)</sup>。

于是虚调用分三步进行：加载接收者的虚表指针，用编译期常量槽位号索引虚表，再通过加载到的地址跳转<sup>[3](https://www.learncpp.com/cpp-tutorial/the-virtual-table/)</sup><sup> • </sup><sup>[7](https://dl.acm.org/doi/10.1145/236338.236369)</sup>。由于槽位索引是编译期常量，且虚表指针在常见布局中位于偏移零处，因此无论继承深度如何，分派都是两次内存加载加一次间接跳转，即 O(1)<sup>[5](https://cpp.wyattau.com/object_oriented/2_runtime_polymorphism/1_vtables/)</sup>。在 Itanium ABI 中，虚函数指针条目既可以存放函数地址，也可以存放一个次级入口点，由它在移交控制权之前执行调整（例如多继承中的 `this` 指针修正）<sup>[2](https://refspecs.linuxfoundation.org/cxxabi-1.83.html)</sup>。

有两条 C++ 规则与这套机制相互作用。每个虚函数都有一个最终覆盖者（final overrider），即虚调用实际执行的实现<sup>[12](https://cppreference.net/cpp/language/virtual.html)</sup>。而当虚函数从构造函数或析构函数中被调用时，运行的是该类中的最终覆盖者，而非更派生类中的那个，因为在构造或析构期间更派生的类尚不存在<sup>[12](https://cppreference.net/cpp/language/virtual.html)</sup>。

**消息传递与基于选择子的分派。** 鸭子类型语言不把分派绑定在类层次结构上，动态语言允许在运行时添加或删除方法，因此选择子必须比虚表偏移更抽象；JIT 编译器用内联缓存来解决由此产生的缓慢查找<sup>[11](https://www.cl.cam.ac.uk/teaching/1718/L25/5DynamicDispatchandDuckTyping.pdf)</sup>。CPython 3.11 的特化自适应解释器在运行时用类型特化版本就地重写热点字节码<sup>[13](https://peps.python.org/pep-0659/)</sup>。

**JVM。** 文献 [9] 描述的多分派 JVM 实现，通过从精确的接收者类型沿超类链向上扫描，寻找名称与签名完全匹配的方法，并把解析出的方法缓存在常量池中<sup>[9](http://webdocs.cs.ualberta.ca/~paullu/Papers/COOTS2001-HTML/mdj.html)</sup>。规范把 `invokevirtual` 定义为按对象的虚类型分派，即 Java 中的常规方法分派；而 `invokeinterface` 则搜索特定运行时对象所实现的方法，这一结构性差异源于接口没有像单一继承链那样共享的编号<sup>[4](https://notes.camadkins.com/cs/languages/common/dispatch-vtables-fat-pointers-and-dictionaries)</sup>。Sun 的 JVM 解释器会缓存接口分派：`invoke_interface` 保存上次执行所用方法条目的偏移量，先检查该偏移量，失败后再回退到完整搜索<sup>[14](http://lampwww.epfl.ch/teaching/archive/compilation/2007/docs-en/9-oo-dispatch.pdf)</sup>。

## 单分派与多分派

单分派依据一个参数（即接收者）的运行时类型选择方法。多分派将其推广到所有参数。多分派的许多用例可以通过 C++ 那样的运算符重载来解决，但 C++ 迫使程序员选择哪些操作参与分派，这一限制催生了 Julia 的设计<sup>[15](https://arxiv.org/pdf/1808.03370)</sup>。

高效实现才是难点。Craig Chambers 为 Cecil 开发的分派算法，首先把用通用谓词分派模型编写的方法归约为多方法形式，将多分派表示为查找 DAG 中的单分派序列，并把每个单分派编译成一棵混合了类同一性测试、类范围测试和表查找的二叉决策树<sup>[16](https://dl.acm.org/doi/10.1145/320385.320407)</sup>。该算法利用静态类型信息剪除不可达路径，并利用动态剖析信息最小化期望搜索时间<sup>[16](https://dl.acm.org/doi/10.1145/320385.320407)</sup>。JVM 的一个多分派扩展在运行普通单分派代码时基本没有额外开销，基于表的 JVM 会推迟分派表的构建，直到插入第一个可多分派的方法<sup>[9](http://webdocs.cs.ualberta.ca/~paullu/Papers/COOTS2001-HTML/mdj.html)</sup>。

## 语言比较

虚表方案在 Simula、Smalltalk 和 [Modula-3](https://www.edgepedia.org/zh/modula-3) 等单继承语言中占主导地位，而 Eiffel、Beta 和 C++ 等多继承语言则需要更复杂的分派实现<sup>[14](http://lampwww.epfl.ch/teaching/archive/compilation/2007/docs-en/9-oo-dispatch.pdf)</sup>。几乎所有主流 C++ 编译器（GCC、Clang、MSVC）都使用虚表模型<sup>[5](https://cpp.wyattau.com/object_oriented/2_runtime_polymorphism/1_vtables/)</sup>。

**二进制接口。** 由于 Itanium C++ ABI 没有平台相关特性，它可以可移植地构建在任何 C ABI 之上；因此，所有主流架构和许多主流操作系统上的众多 C++ 编译器都将其采纳为标准 C++ ABI<sup>[17](https://itanium-cxx-abi.github.io/cxx-abi/)</sup>。固定虚表布局正是让分别编译的库能够互操作的部分原因：如果一个类没有主基类，ABI 会把虚表指针分配在偏移零处<sup>[4](https://notes.camadkins.com/cs/languages/common/dispatch-vtables-fat-pointers-and-dictionaries)</sup>。

**Rust 与 Go。** Rust 把虚表放在引用而非对象中：每个指向 `dyn Trait` trait 对象的指针都携带一个数据指针加一张虚表，即胖指针<sup>[4](https://notes.camadkins.com/cs/languages/common/dispatch-vtables-fat-pointers-and-dictionaries)</sup>。Go 在泛型上做了相反的权衡：对泛型函数的调用携带一个静态定义的编译期字典，其中包含运行时类型描述符、派生类型、子字典和 itab，因此泛型函数内受约束的方法调用是一次通过字典提供的 itab 解析的接口调用，而 Rust 会把同样的调用单态化为直接调用<sup>[4](https://notes.camadkins.com/cs/languages/common/dispatch-vtables-fat-pointers-and-dictionaries)</sup>。

## 性能与优化

缓存命中时，虚调用的直接开销在现代硬件上约为 2–5 个周期；主要代价在于阻止了内联，以及间接跳转可能发生分支预测失败<sup>[5](https://cpp.wyattau.com/object_oriented/2_runtime_polymorphism/1_vtables/)</sup>。在 Java 中，虚调用转换为两次依赖加载加一次间接跳转，而在 [Pentium III](https://www.edgepedia.org/zh/pentium-iii) 上分支解析通常发生在 10–20 个流水线周期之后<sup>[8](https://static.usenix.org/event/jvm02/full_papers/zendra/zendra_html/index.html)</sup>。[分支预测](https://www.edgepedia.org/zh/branch-prediction)很重要：在 2 位分支目标缓冲上，虚调用的 [BTB](https://www.edgepedia.org/zh/branch-target-buffer) 缺失率从 1.2%（Deltablue）到 27.1%（Richards）不等，而 2 位预测技术优于 1 位，因为 1 位改变预测过于频繁<sup>[18](https://www.usenix.org/legacy/publications/library/proceedings/coots99/full_papers/vijaykrishnan/vijaykrishnan.pdf)</sup><sup> • </sup><sup>[19](https://cseweb.ucsd.edu/~calder/papers/POPL-94.pdf)</sup>。

**去虚化。** 在 `-O2` 或 `-O3` 下，当动态类型可证明时，C++ 编译器可能完全消除虚分派；把类或函数标记为 `final`，或使用 [CRTP](https://www.edgepedia.org/zh/curiously-recurring-template-pattern) 或 C++23 的 deducing-this，都能启用静态分派<sup>[5](https://cpp.wyattau.com/object_oriented/2_runtime_polymorphism/1_vtables/)</sup>。HotSpot 在运行时通过内联缓存运用这一概念：当虚调用第一次运行时，HotSpot 将其替换为受类型测试保护的直接调用，测试失败则回退到另一个目标；随后类型分析可以对已证明为单态的调用去虚化，使其得以内联<sup>[8](https://static.usenix.org/event/jvm02/full_papers/zendra/zendra_html/index.html)</sup>。

**内联缓存与多态内联缓存。** 为 Self 开发的多态内联缓存把单次检查缓存扩展到若干预期接收者类型，空间开销极低，通常不到编译代码的 2%<sup>[20](https://brenocon.com/self%20-%20polymorphic%20inline%20caching%20-%20ecoop91.pdf)</sup>。受保护的去虚化有其自身代价：它把单个间接分支转换为多个保护测试和直接调用，从而增加静态代码体积<sup>[21](https://users.ece.cmu.edu/~omutlu/pub/TR-HPS-2007-002.pdf)</sup>。硬件也能帮忙：VPC 预测根据虚调用历史预测间接分支目标，使面向对象的 Java DaCapo 应用平均性能提升 21.9%，在一半的应用上需要至少 12KB（通常 192KB）的带标记目标缓存<sup>[21](https://users.ece.cmu.edu/~omutlu/pub/TR-HPS-2007-002.pdf)</sup>。

**解释器分派。** 同样的问题也出现在解释器内部。CPython 的计算跳转解释器为每个操作码生成一份独立的分派跳转副本，以便向硬件分支目标预测器暴露更多信息，并用空的 `__asm__ volatile` 屏障阻止编译器将它们合并，在 pyperformance 上实测运行速度为原来的 1.03 倍<sup>[22](https://github.com/python/cpython/issues/129987)</sup>。CPython 3.11 的特化带来了 10%–60% 的加速，贡献最大的是属性查找、全局变量和调用<sup>[13](https://peps.python.org/pep-0659/)</sup>，而建立在其上的 CPython JIT 消除了微操作之间的分派开销、指令解码开销和内存流量，代价是比基础解释器多约 10%–20% 的内存<sup>[23](https://peps.python.org/pep-0744/)</sup>。

## 数据一览

实测程序让这些代价变得具体。经典的 C++ 研究发现，程序花在分派代码上的执行时间占比中位数为 5.2%，指令数占比中位数为 3.7%，对于“全虚函数”版本，中位数升至 13.7%（指令数 13%），最高达 47%<sup>[7](https://dl.acm.org/doi/10.1145/236338.236369)</sup>。对某些程序而言，分派优化可使执行时间相差多达 50%<sup>[8](https://static.usenix.org/event/jvm02/full_papers/zendra/zendra_html/index.html)</sup>。

一项当代 C++ 基准测得每次虚调用 2.90 纳秒，直接调用为 1.48 纳秒，相差 +1.42 纳秒，函数指针为 2.43 纳秒，`std::variant` + `std::visit` 为 3.71 纳秒<sup>[6](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)</sup>。代码体积也会增长：虚分派构建产生的 text 段为 6,776 字节，比 4,727 字节的函数指针基线大 43%，而解耦的 CRTP 达到 7,885 字节（+67%），分派开销与函数指针相当，但需要 346 行代码，而后者只需 90 行<sup>[6](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)</sup>。

内存代价按对象和按类计算。虚表指针字段在 64 位 Itanium 上为 8 字节，因此一百万个小的多态对象要花 8 兆字节在分派元数据上<sup>[4](https://notes.camadkins.com/cs/languages/common/dispatch-vtables-fat-pointers-and-dictionaries)</sup>。实现选择的影响可以测量：虚表实现的 thunk 变体相对于标准实现，将分派开销中位数降低了 21%<sup>[7](https://dl.acm.org/doi/10.1145/236338.236369)</sup>。

## 历史

虚函数表最早由 Simula 使用，C++ 将其采纳为首选的分派机制<sup>[7](https://dl.acm.org/doi/10.1145/236338.236369)</sup>。[Alan Kay](https://www.edgepedia.org/zh/alan-kay) 早期的 Smalltalk（-71）受 FLEX、PLANNER、LOGO 和 META II 影响，被描述为一种带有对象附着、直接执行记号（token）的解析器，确立了消息传递作为动态语言分派模型的地位<sup>[24](https://www.cs.tufts.edu/~nr/cs257/archive/alan-kay/smalltalk-hopl-ii.pdf)</sup>。后来的工作把优化移入运行时：Self 的 JIT 中的内联缓存、HotSpot 中的[类型反馈](https://www.edgepedia.org/zh/type-feedback)与内联缓存，以及今天 CPython 3.11 这类特化解释器——它在运行时用类型特化版本就地重写字节码<sup>[20](https://brenocon.com/self%20-%20polymorphic%20inline%20caching%20-%20ecoop91.pdf)</sup><sup> • </sup><sup>[8](https://static.usenix.org/event/jvm02/full_papers/zendra/zendra_html/index.html)</sup><sup> • </sup><sup>[13](https://peps.python.org/pep-0659/)</sup>。

## References

1. [C++17 draft, [class.virtual]](https://timsong-cpp.github.io/cppwp/std17/class.virtual)
2. [Itanium C++ ABI, version 1.83](https://refspecs.linuxfoundation.org/cxxabi-1.83.html)
3. [25.6 — The virtual table, Learn C++](https://www.learncpp.com/cpp-tutorial/the-virtual-table/)
4. [Dispatch, Vtables, Fat Pointers, and Dictionaries](https://notes.camadkins.com/cs/languages/common/dispatch-vtables-fat-pointers-and-dictionaries)
5. [Virtual Functions and vtables, C++](https://cpp.wyattau.com/object_oriented/2_runtime_polymorphism/1_vtables/)
6. [cpp-dispatch-benchmark](https://github.com/Shubhankar-Gambhir/cpp-dispatch-benchmark)
7. [The direct cost of virtual function calls in C++, OOPSLA](https://dl.acm.org/doi/10.1145/236338.236369)
8. [Quantifying Performance Constraints of Dynamic Dispatch in the Java Virtual Machine, JVM '02](https://static.usenix.org/event/jvm02/full_papers/zendra/zendra_html/index.html)
9. [Multi-Dispatch in the Java Virtual Machine: Design and Implementation, COOTS 2001](http://webdocs.cs.ualberta.ca/~paullu/Papers/COOTS2001-HTML/mdj.html)
10. [Multiple dispatch in practice, OOPSLA 2008](https://psycnet.apa.org/doi/10.1145/1449764.1449808)
11. [Dynamic Dispatch and Duck Typing, Cambridge L25 lecture notes](https://www.cl.cam.ac.uk/teaching/1718/L25/5DynamicDispatchandDuckTyping.pdf)
12. [virtual function specifier, cppreference](https://cppreference.net/cpp/language/virtual.html)
13. [PEP 659 – Specializing Adaptive Interpreter](https://peps.python.org/pep-0659/)
14. [Part IX: Object-Oriented Dispatch Methods, EPFL compilation course notes](http://lampwww.epfl.ch/teaching/archive/compilation/2007/docs-en/9-oo-dispatch.pdf)
15. [Multiple dispatch in Julia, arXiv](https://arxiv.org/pdf/1808.03370)
16. [Efficient multiple and predicated dispatching, ACM SIGPLAN Notices](https://dl.acm.org/doi/10.1145/320385.320407)
17. [Itanium C++ ABI overview](https://itanium-cxx-abi.github.io/cxx-abi/)
18. [Tuning Branch Predictors to Support Virtual Method Calls, USENIX COOTS '99](https://www.usenix.org/legacy/publications/library/proceedings/coots99/full_papers/vijaykrishnan/vijaykrishnan.pdf)
19. [Reducing Indirect Function Call Overhead in C++ Programs, POPL '94](https://cseweb.ucsd.edu/~calder/papers/POPL-94.pdf)
20. [Polymorphic Inline Caching, ECOOP '91](https://brenocon.com/self%20-%20polymorphic%20inline%20caching%20-%20ecoop91.pdf)
21. [VPC Prediction: Reducing the Cost of Indirect Branches via Hardware-Based Dynamic Devirtualization](https://users.ece.cmu.edu/~omutlu/pub/TR-HPS-2007-002.pdf)
22. [computed-goto interpreter: Prevent the compiler from merging DISPATCH calls, CPython issue 129987](https://github.com/python/cpython/issues/129987)
23. [PEP 744 – JIT Compilation](https://peps.python.org/pep-0744/)
24. [The Early History of Smalltalk, Alan Kay, HOPL II](https://www.cs.tufts.edu/~nr/cs257/archive/alan-kay/smalltalk-hopl-ii.pdf)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Programming languages › Programming language concepts

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/dynamic-dispatch

English original: https://www.edgepedia.org/dynamic-dispatch
