Speed of multiple dispatch

Note that items is of type Vector{Any}. With a narrower type, both paths are faster, the dispatch code equally fast. (Only for sufficiently small unions.)

julia> rand([S1(), S2()], 3)
3-element Vector{Any}:
 S2()
 S1()
 S2()

julia> rand(Union{S1,S2}[S1(), S2()], 3)
3-element Vector{Union{S1, S2}}:
 S1()
 S2()
 S2()

I believe that the reason dynamic dispatch is slower is that the code compiled for Vector{Any}) cannot exploit the knowledge that do_dispatch has exactly 4 methods. This may change (e.g. you could define struct S3) and the I don’t think the compiled code will be discarded.

Whereas the code for Vector{Union{S1, S2}} is going to be essentially the same branches you wrote, probably inlining do_dispatch. This code can never encounter some new S3, and I believe it will be thrown away if you change the definitions of do_dispatch it uses.

8 Likes