[fpc-devel] Using case statement instead of VTable

Marco van de Voort fpc at pascalprogramming.org
Tue Apr 11 09:58:14 CEST 2023


On 11-4-2023 07:23, Hairy Pixels via fpc-devel wrote:
> Strange question but I heard it brought up during a discussion and I was very curious what compiler people think about it.

I hope you don't mind me replying as non compiler person :-)

>
> The question is, instead of using a virtual method table would it be feasible to use a case statement on the real class type and make a dispatch routine for each method call?
>
> For example assume “type” is the internal type of the class (where a VTable would be) and a call to “animal.DoSomething()” is called which would internally basically be this dispatch table:
>
>   case animal.type of
>     TDog: TDog(animal).DoSomething;
>     TCat: TCat(animal).DoSomething;
>     TMouse: TMouse(animal).DoSomething;
>   end;

This doesn't happen. There is no class that is TDog,Cat and mouse. 
Usually a VMT governs the relation between parent and child, i.e.   TDog 
and TAnimal.  The TDog nor the TAnimal implementation has no knowledge 
of the other mammals.


> The reason this was brought up was because virtual methods can’t be inlined and this would allow that but I think there would be more overhead overall to have all these case statements on every virtual method call.

Much more, keep in mind your example above doesn't even have parameters.

Keep in mind that the virtual call is fairly cheap to begin with, you 
load the VMT from the instance references (first field), and then the 
method pointer at an fixed offset relative to that. Two instructions on 
x86 with its many addressing modes, only slightly more on non-x86, I 
would guess, and no branches.

Your solution would also need to load some reference to the class type, 
(the first instruction) and then a compare and branch for each case.

But the core problem is that you don't have an overview of all other 
descendants in the compiler. Those can be fragmented over multiple 
units, and then you touch the problem that whole program optimization 
like de-virtualization tries to solve.



More information about the fpc-devel mailing list