Reading some old posts on caml-list I came across the following post by Jacques Garrigues: http://caml.inria.fr/pub/ml-archives/caml-list/2007/11/24e8215c8d844b05db58ed3f79c9645f.en.html
The quote that I care about is the following:
Method calls on arbitrary objects can be slow. This is because, due to
subtyping, in some situations there is no way to know where the method
will be in the table, and a binary search has to be done.
Can anybody explain why this is the case? Why exactly subtyping (inheritance I’m assuming in this case) is affecting this? Is this the case for OCaml’s implementation or do other languages suffer from this as well?
Please point me towards further resources regarding this, google has failed me.
With nominal typing each method can be assigned a unique integer at compile time so a virtual function can be found by indexing into an array. With structural typing (as in OCaml) this cannot be done so a hash of the structure (i.e. method name) is used to search for virtual method’s function pointer in a dictionary.
Subtypes are a prerequisite for virtual dispatch.
Just OCaml’s implementation. In F#, I have used reflection and run-time code generation to achieve the same effect with no such invoke-time performance hit.