Converting Boolean to Integer in Java without If-Statements

后端 未结 12 1962
盖世英雄少女心
盖世英雄少女心 2020-12-30 02:26

I\'m wondering if there\'s a way to convert a boolean to an int without using if statements (as not to break the pipeline). For example, I could write

int bo         


        
12条回答
  •  孤城傲影
    2020-12-30 02:51

    You can't use a boolean other than in a if. However it does not mean that there will be a branch at the assembly level.

    If you check the compiled code of that method (by the way, using return b ? 1 : 0; compiles to the exact same instructions), you will see that it does not use a jump:

    0x0000000002672580: sub    $0x18,%rsp
    0x0000000002672587: mov    %rbp,0x10(%rsp)    ;*synchronization entry
    0x000000000267258c: mov    %edx,%eax
    0x000000000267258e: add    $0x10,%rsp
    0x0000000002672592: pop    %rbp
    0x0000000002672593: test   %eax,-0x2542599(%rip)        # 0x0000000000130000
                                                    ;   {poll_return}
    0x00000000025b2599: retq  
    

    Note: this is on hotspot server 7 - you might get different results on a different VM.

提交回复
热议问题