Which is faster, and why? Or is the difference too small to be significant?
I doubt such code would make a difference to modern optimizers, but if you want to know, we first would have to ask, What platform, what compiler?, and then we would need to measure.
Is one of them is more dynamic? Is there a reason one of them may fall short to the other in certain scenarios?
As I happen to believe that your compiler's optimizer can deal with all of them equally, I would suggest to write code that's easy to understand and maintain and deal with optimizations only after measuring reveals that this is a hotspot.
Which is the better/preferred code, or is the practice of either entirely opinion based?
Over time, I have found that I am leaning more and more towards the functional paradigm. I like expressing branches through the code's structure better than through variable values, I prefer to constify as much as possible (even locale variables).
I have especially learned to dislike code like this:
int x;
if( some_condition )
x = 5;
else
x = 42;
In order to understand what code like this does, one has to track the values of each variable and follow each statement. Also, x
cannot be const
here, which I consider a string disadvantage.
I strongly prefer
const int x = calc_x(some_condition);
which, in cases as easy as this example, can be written as
const int x = some_condition ? 5 : 42;
Now x
can be const
(allowing the compiler to prevent me from unintentionally doing silly things), the piece of code implementing the algorithm that finds out what x
ought to be has a name (calc_x()
), and rather than having the algorithm inline
, now only that name is in the code.
Of course, this code is so simple that it doesn't really need the benefits I am listing, but when you deal with more complex real-world code, I have found that, in the long run, a more functional approach is be better.