Branching on algorithmic options - advice on code organization

A situation I encounter pretty frequently is the need to modify the behavior of an algorithm according to some boolean (or more general) “options” parameters.
A plain if-else statement evaluated at runtime can be costly for a critical portion of the code (although in practice, I am not if this is indeed the case) that gets evaluated many times.

My question (more of advice) is which coding approach for the above is preferable in terms of readability, reusability, and performance.

Two approaches that come to mind are:

  1. Parametric types – the branching is (presumably) evaluated at compile time since the type parameter is known and multiple dispatch can be utilized. One issue with that is the need to “fully” specify all parameters at invocation, which might be hard to maintain when parameters are removed or added in a future version of the code.

  2. Encoding the parameter as a field object of a composite type and then branch according to its values.
    Potentially slower, it seems more straightforward to implement.

I hope my situation is clear and not too abstract.

Is there a preferred “Julian” approach?

Could you maybe provide an example of something you are trying to optimize please?

If it’s just a Boolean for choosing different options, and the Boolean doesn’t change during the computation, the microprocessor’s branch predictor will quickly learn the correct branch and there won’t be a performance impact.

1 Like

Keyword Arguments are an easy and common way to add options to a function.

You can also sort of combine #1 and #2 as illustrated here.