Is if(var == true) faster than if(var != false)?

后端 未结 10 1022
礼貌的吻别
礼貌的吻别 2020-12-18 18:25

Pretty simple question. I know it would probably be a tiny optimization, but eventually you\'ll use enough if statements for it to matter.

EDIT: Thank you to those o

10条回答
  •  失恋的感觉
    2020-12-18 18:56

    Knowing which of these two specific cases is faster is a level of detail that is seldom (if ever) required in a high-level language. Perhaps you might require to know it if your compiler is piss poor at optimizations. However, if your compiler is that bad, you would probably be better off overall in getting a better one if possible.

    If you are programming in assembly, it is more likely that you knowledge of the two cases would be better. Others have already given the assembly breakdown with respect to branch statements, so I will not bother to duplicate that part of the response. However, one item that has been omitted in my opinion is that of the comparison.

    It is conceivable that a processor may change the status flags upon loading 'var'. If so, then if 'var' is 0, then the zero-flag may be set when the variable is loaded into a register. With such a processor, no explicit comparison against FALSE would be required. The equivalent assembly pseudo-code would be ...

    load 'var' into register
    branch if zero or if not zero as appropriate
    

    Using this same processor, if you were to test it against TRUE, the assembly pseudo-code would be ...

    load 'var' into register
    compare that register to TRUE (a specific value)
    branch if equal or if not equal as appropriate
    

    In practice, do any processors behave like this? I don't know--others will be more knowledgeable than I. I do know of some that don't behave in this fashion, but I do not know about all.

    Assuming that some processors do behave as in the scenario described above, what can we learn? IF (and that is a big IF) you are going to worry about this, avoid testing booleans against explicit values ...

    if (var == TRUE)
    if (var != FALSE)
    

    and use one of the following for testing boolean types ...

    if (var)
    if (!var)
    

提交回复
热议问题