Inspired from my most favorite stackoverflow question I'm trying to decide what is more 'convenient' when facing up a classical problem in programming, i.e. executing some code instead some other according to any current scenario.
To make it brief, imagine an application can be in 2 different states and has to execute some code according to this state.
(switching to C++ context, which I'm more interested to)
The usual approach would be to store status in a bool
and use an if
to decide which branch to execute.
A different approach is to wrap the 2 branches of code in 2 different functions and store the status in a function pointer: whenever suitable code shall be executed the application has just to call pointed function, no if
involved.
Now, in addition to lazily asking your opinions on which of two strategies is more 'convenient', I approximated 'convenient'=='fastest' so I set up a benchmark whose code you can read here, and executed it also on my machine compiling with MSVC2017.
Each compiler returns different results (in my MSVC function pointer strategy is slower, in online GCC is faster) but what surprises me is function pointer strategy is always slower when switching status while I was expecting times to be very similar to non switching situation: why?
Thank you.
NOTE: increase value std::uint64_t N = 100'000'000;
for significant results as online compiler would timeout.