Multiple dispatch vs visitor pattern

I think that it’s cool that crystal supports multiple dispatch just like Julia lang. I noticed that the compiler doesn’t utilize this functionality and uses classic visitor pattern, is there a reason for that? I’m guessing there must be some overhead in using multiple dispatch?

The compiler does use multiple dispatch here

1 Like

Nice to see it showcased within the compiler, is there a reason why we don’t just use it instead of visitor pattern or is it just a design choice?
So there aren’t any performance penalty using it?
In Nim lang they decided to remove this feature because of performance/complexity here in this issue, so there must be some drawbacks?

Let me note that the visitor pattern in Crystal still uses method-dispatch under the hood, simply because every time the compiler needs to dispatch to pick a specific overload when the object has a generic type (like ASTNode).

Therefore, the pick of the visitor pattern is just a design one. It allows you to simply focus on the specific values you care. Otherwise, you need a big case ... when statement.

1 Like

Thanks for answering my question about method dispatching, good to know that all dispatching are using the same strategy under the hood. I am not sure I understand the thing about a big case ... when

I thought you could mitigate the need for cases like this:

class AstPrinter

def visit(node : ASTNode)
  visit(node) #dispatches to the right method
end 

def visit(node : Assign)
   ...
end

def visit(node : TypeDeclaration)
    ...
end
...
end

You’re right. I have no idea why I mentioned the case thing. Answering a question that wasn’t placed :sweat_smile:

1 Like