vtable 的替代方案
Vtables 在大多数 OO 实现中无处不在,但是它们有替代方案吗? vtables 的 wiki 页面有一个简短的简介,但实际上并没有太多信息(和存根链接)。
你知道一些不使用虚函数表的语言实现吗?
是否有讨论替代方案的免费在线页面?
Vtables are ubiquitous in most OO implementations, but do they have alternatives? The wiki page for vtables has a short blurb, but not really to much info (and stubbed links).
Do you know of some language implementation which does not use vtables?
Are there are free online pages which discuss the alternatives?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,有很多选择!
仅当满足两个条件时,虚拟表才有可能。
通常,继承是通过使用基于字符串的表将函数名称映射到其实现以及允许每个类查找其基类的指针来实现的。然后通过遍历该结构寻找实现该方法的接收者对象的类或之上的最低类来实现方法调度。为了加快执行速度,经常使用内联缓存等技术,其中调用站点根据对象的类型存储应调用哪个方法的猜测,以避免花费时间遍历整个结构。 Self 编程语言使用了这个想法,然后将其合并到 HotSpot JVM 中来处理接口(标准继承仍然使用 vtable)。
另一种选择是使用跟踪,其中编译器发出代码来猜测对象的类型,然后将要调用的方法硬编码到跟踪中。 Mozilla Firefox 在其 JavaScript 解释器中使用它,因为没有办法为每个对象构建 vtable。
我刚刚教授完编译器课程,我的其中一堂讲座是关于各种编程语言中对象的实现以及相关的权衡。如果您愿意,可以在此处查看幻灯片 。
希望这有帮助!
Yes, there are many alternatives!
Vtables are only possible when two conditions hold.
Commonly, inheritance is implemented by having a string-based table mapping names of functions to their implementations, along with pointers allowing each class to look up its base class. Method dispatch is then implemented by walking this structure looking for the lowest class at or above the class of the receiver object that implements the method. To speed up execution, techniques like inline caching are often used, where call sites store a guess of which method should be invoked based on the type of the object to avoid spending time traversing this whole structure. The Self programming language used this idea, which was then incorporates into the HotSpot JVM to handle interfaces (standard inheritance still uses vtables).
Another option is to use tracing, where the compiler emits code that guesses what the type of the object is and then hardcodes the method to call into the trace. Mozilla Firefox uses this in its JavaScript interpreter, since there isn't a way to build vtables for every object.
I just finished teaching a compilers course and one of my lectures was on implementations of objects in various programming languages and the associated tradeoffs. If you'd like, you can check out the slides here.
Hope this helps!