知识卡片
静态与动态分派
Screen 中每个实例选定一个 T,编译器为实际使用的具体类型生成实现,直接确定被调方法。Vec> 可容纳多种实现,同一处调用在运行时从对应方法表选取方法,要付出间接调用成本,内联机会也可能减少。类型集合固定时可用枚举,同构集合可用泛型,需要让调用方扩展异构实现时可用特征对象。
相关卡片 [[特征对象统一异构组件]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 面向对象编程特性 Using Trait Objects That Allow for Values of Different Types · 查看原书依据
When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t know all the types that might be used with the code that’s using trait objects, so it doesn’t know which method implemented on which type to call. Instead, at runtime, Rust uses the pointers inside the trait object to know which method to call. This lookup incurs a runtime cost that doesn’t occur with static dispatch.
参考来源
- 位置:《The Rust Programming Language(第2版)》第17章 面向对象编程特性(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c17.xhtml`,块 0087)
- 结论依据:原文说明运行时方法表查找的开销与内联限制,并将其与异构组件的灵活性权衡。
- 原始内容:When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t know all the types that might be used with the code that’s using trait objects, so it doesn’t know which method implemented on which type to call. Instead, at runtime, Rust uses the pointers inside the trait object to know which method to call. This lookup incurs a runtime cost that doesn’t occur with static dispatch.