Reputation:
I wonder if it's worth to make computation one time and store the result or it's faster to do twice the computation?
For example in this case:
float n1 = a - b;
float n2 = a + b;
float result = n1 * n2 / (n1 * n2);
Is it better to do:
float result = (a - b) * (a + b) / ((a - b) * (a + b));
? I know that normally we store the result but I wonder if it's not faster to do the addition instead of calling the memory to store/retrieve the value.
Upvotes: 3
Views: 378
Reputation: 5151
It really depends: For trivial examples like yours, it does not matter. The compiler will generate the same code, since it finds the common sub-expressions and eliminates the duplicated calculations.
For more complicated examples, for example involving function calls, you are better off to use the first variant, to "store" intermediate results. Do not worry about using simple variables for intermediate storage. These are usually all kept in CPU registers, and the compiler is quite good in keeping values in registers.
The danger is that with more complex calculations the compiler may fail to do the common sub-expression elimination. This is for example the case when your code contains function calls which act like a compiler boundary.
Another topic is that with floating point, even simple operations like addition are not associative, i.e. (a+b)+c is different from a+(b+c), due to artifacts in the lowest bits. This often also prevents common subexpression elimination, since the compiler is not allowed to change the semantics of your code.
Upvotes: 6
Reputation: 5222
Dividing the expression into smaller expressions and giving them sensible names gives You several benefits:
In C++ a temporary variable could also be marked const
, then this also allows the compiler to better optimize the expressions.
But optimizations should be measured before they are discussed and used as arguments. Fast usually comes from the choice of data structures and used algorithms.
In general code should be written to be understood and be correct, and only then should it be optimized.
const float difference = a - b;
const float sum = a + b;
const float result = difference * sum / (difference * sum);
Upvotes: 1