简体   繁体   中英

Eliminate inefficient code

I was wondering if one is inefficient over the other (two codes below)?

if ( abc & myType == myType ) 
{
    if (myValue)
    {
        // do something
    }
}

OR

if ( (abc & myType) && myValue ) 
{
    // do something
}

They are not equivalent, a "corrected" second one would be

if ( (abc & myType == myType) && myValue ) 
{
    // do something
}

In this case, any decent compiler will emit the same code for both.

Also, it's almost never sensible to do this kind of micro-optimization - you waste time around a difference that will be at most of one or two assembly instruction, maybe even in a code path that isn't critical. Here, where there's no real difference in performance, the real optimization to do is towards clarity of your code.

Real optimization is about not caring about these micro-differences (which are probably already taken of by the compiler), and instead profiling the code to find the real bottlenecks.

A few others have pointed out that the two are not equivalent for this reason:

if (abc & myType == myType ) 
{
    if (myValue) {}
}

// OR

if ( (abc & myType) && myValue ) // missing myType == myType
{}

However there is a second reason the two are not equivalent: the == operator has higher precedence than the & operator ( see this link ). Your first expression therefore evaluates as follows:

if (abc & myType == myType) // Evaluates to (abc & true)
{
    if (myValue) {}
}

You probably intended this:

if ((abc & myType) == myType) // Now the bitwise and happens before
                              // the comparison is made
{
    if (myValue) {}
}

To avoid exactly this kind of bug, I always use parentheses to enforce precedence any time there is any possibility of ambiguity from a human's perspective (even though the compiler will never find it ambiguous), on the assumption that the reader has no clue what the actual precedences are. This has the added benefit of making the code easier to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM