Refactor a condition [closed]

2019-09-22 04:12发布

问题:

There is a condition for a,b,c,d,e,f,g of type unsigned int given as follows:

if ((a > 0) and (b < a) and (c >= d))
{
    return ((e < std::min(std::max(0, a - g), b)) and 
            (f < std::min(d, std::max(0, c - g))));
}

I am looking for the way of refactoring the expression to make it more readable.

回答1:

Optimization was the wrong term, but the code can be rewritten to find a better (more reduced, or succinct to the business) logic.

X < min(Y, Z)    <=>    X < Y and X < Z
X < max(Y, Z)    <=>    X < Y or X < Z            (less usefull)

Then possible rewrites are

return ((e < std::min(std::max(0, a - g), b)) and 
        (f < std::min(d, std::max(0, c - g))));

return ((e < std::max(0, a - g) and e < b)) and 
        (f < d and  f < std::max(0, c - g))));

return (e < 0 or e < a - g)
       and e < b
       and f < d
       and (f < 0 or f < c - g);

Depending on other constraints this might be reducable.

I would rather make a function between for the hard to read min+max.

return e < minmax(b, a - g, 0) and 
       f < minmax(d, c - g, 0);

I did not call this between, as maxmin is feasible too.


Added

@Jarod pointed me to the fact, that the OP mentioned all numbers would be unsigned. Then

max(a - g, 0)

probably should have been

a > g ? a - g : 0


回答2:

First of all, leave such low level optimizations to your C++ compiler. Probably a recent GCC invoked as g++ -Wall -O2 -march=native will optimize better than you do. See Matt Goldbolt's CppCon2017 talk: What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid.

If you believe (after profiling) that this particular piece of code should be optimized by hand, do so and document it. But you should profile first.

Be aware of the various approximate timing of computations.

Remember that development time has its costs also. Most of the time they are more important than such low-level optimizations. Hence readability of the source code is also important (better naming of variables, extra temporary values, or additional comments could be important).