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

后端 未结 10 1036
礼貌的吻别
礼貌的吻别 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 19:08

    It will make absolutely zero difference, because the compiler would almost certainly compile the two statements to the same binary code.

    The (pseudo) assembly will either be:

    test reg1, reg2
    br.true somewhere
    ; code for false case
    
    somewhere:
    ; code for true case
    

    or

    test reg1, reg2
    br.false somewhere
    ; code for true case
    
    somewhere:
    ; code for false case
    

    Which of those the compiler chooses will not depend on whether you write == true or != false. Rather, it's an optimisation the compiler will make based on the size of the true and false case code and perhaps some other factors.

    As an aside, the Linux kernel code actually does try to optimise these branches using LIKELY and UNLIKELY macros for its if conditions, so I guess it is possible to manually control it.

提交回复
热议问题