12

阅读 caml-list 上的一些旧帖子时,我发现了 Jacques Garrigues 的以下帖子:http: //caml.inria.fr/pub/ml-archives/caml-list/2007/11/24e8215c8d844b05db58ed3f79c9645f.en.html

我关心的报价如下:

对任意对象的方法调用可能很慢。这是因为,由于子类型化,在某些情况下无法知道方法在表中的位置,因此必须进行二分查找。

谁能解释为什么会这样?为什么确切的子类型(我在这种情况下假设的继承)会影响这一点?这是 OCaml 实现的情况,还是其他语言也受此影响?

请向我指出有关此的更多资源,谷歌让我失望了。

4

2 回答 2

10

I think that delnan's comment that, in OCaml, “Subtyping != inheritance” holds the insight to the explanation.

$ rlwrap ocaml
        OCaml version 4.00.1

# let f o = o#x + o#y ;;
val f : < x : int; y : int; .. > -> int = <fun>
# 

Function f above accepts any object o that has methods x : int and y : int. Not objects that inherit from some class c in which an offset for these methods could have been fixed in advance, mind you. Any object with these methods. I guess this is difficult to implement, and may be one of the cases Jacques is referring to in his message.

于 2012-12-09T00:20:02.010 回答
4

谁能解释为什么会这样?

通过标称类型,可以在编译时为每个方法分配一个唯一的整数,因此可以通过索引到数组中找到虚函数。对于结构类型(如在 OCaml 中),这是无法做到的,因此结构的散列(即方法名称)用于在字典中搜索虚拟方法的函数指针。

为什么确切的子类型(我在这种情况下假设的继承)会影响这一点?

子类型是虚拟调度的先决条件。

这是 OCaml 实现的情况,还是其他语言也受此影响?

只是 OCaml 的实现。在 F# 中,我使用反射和运行时代码生成来实现相同的效果,而不会影响调用时性能。

于 2013-02-07T18:56:48.223 回答