Ask for advise : Multiple dispatch vs branching performance

Maucejo
Mon, 13 Jan 2025 09:13:41 +0000
General Usage

Hi all,

I am developing a package for generating structural vibration data, which I hope to release to the community once it is finished. In the course of development, I am faced with a dilemma between multiple dispatch and branching.

I have implemented several structures to define a problem to be solved, such as struct XXProblem ... end. Currently I have about 20 such structures. I have also defined some structures to implement some solvers (like Newmark’s method). Each of these structures is currently used to multiple dispatch a solve function.

My question is : From a performance perspective, is it better to use multiple dispatch or branching ? To illustrate my question, here are two possible implementations of the solve function:

# Multiple dispatch
function solve(prob::XXProblem, u0, params, alg::SolverA())
...
end

function solve(prob::XXProblem, u0, params, alg::SolverB())
...
end

# Branching
function solve(prob::XXProblem, u0, params, alg::AbstractSolver)
   if alg isa SolverA
      sol = _solveA(prob, u0, params)
   else
     sol = _solveB(prob, u0, params)
   end
end

I know I can implement both and use BenchmarkTools to answer this question. But before I do, I wonder if any of you have any experience with this question.

Another related question: What do you recommend to precompile using PrecompileTools ? All the solve functions ? Only the longest version to precompile ?

Thank you

8 posts - 5 participants