Why '&&' and not '&'?

前端 未结 16 1512
别跟我提以往
别跟我提以往 2020-11-27 12:11

Why is && preferable to & and || preferable to |?

I asked someone who\'s been programming for years a

16条回答
  •  一整个雨季
    2020-11-27 13:05

    To explain very clearly what this means (even though the other answers hint at it - but probably use terminology you don't understand).

    The following code:

    if (a && b)
    {
       Foo();
    }
    

    Is really compiled to this:

    if (a)
    {
        if (b)
        {
            Foo();
        }
    }
    

    Where the following code is compiled exactly as it is represented:

    if (a & b)
    {
       Foo();
    }
    

    This is called short-circuiting. In general you should always use && and || in your conditions.

    Bonus Marks: There is one scenario when you shouldn't. If you are in a situation where performance is crucial (and this is nano-seconds crucial) only use short-circuiting when you must (e.g. null checking) - as a short-circuit is a branch/jump; which could result in a branch-misprediction on your CPU; an & is much cheaper than &&. There is also a scenario where short-circuiting can actually break logic - have a look at this answer of mine.

    Diatribe/Monologue: Regarding the branch mis-prediction that most blissfully ignore. Quoting Andy Firth (who has been working on games for 13 years): "This may be lower level that people think they need to go... but they'd be wrong. Understanding how the hardware you're programming for treats branches can affect performance to a HUGE degree... far more than most programmers may appreciate re: death by a thousand cuts."

    • Game developers (and others working in extreme real-time conditions) go as far as restructuring their logic to better suit the predictor. There is also evidence of this in decompiled mscorlib code.
    • Just because .NET shields you from this type of thing doesn't mean it's not important. A branch mis-prediction is horribly expensive at 60 Hz; or at 10,000 requests/second.
    • Intel wouldn't have tools to identify the location of mis-predictions, nor would Windows have a performance counter for this, nor would there be a word to describe it, were it not a problem.
    • Ignorance about the lower levels and architecture does not make someone who is aware of them wrong.
    • Always try to understand the limitations of the hardware you are working on.

    Here is a benchmark for the non-believers. It's best to run the process in RealTime/High to mitigate the scheduler having an effect: https://gist.github.com/1200737

提交回复
热议问题