在没有 If 语句的情况下在 Java 中将布尔值转换为整数
我想知道是否有一种方法可以在不使用 if 语句的情况下将布尔值转换为 int(以免破坏管道).例如,我可以写
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 boolToInt( boolean b ){
if ( b )
return 1
return 0
但我想知道是否有办法在没有 if 语句的情况下做到这一点,就像 Python 的
But I'm wondering if there's a way to do it without the if statement, like Python's
bool = True
num = 1 * ( bool )
我也觉得你可以做
boolean bool = True;
int myint = Boolean.valueOf( bool ).compareTo( false );
不过,这会创建一个额外的对象,所以它真的很浪费,我发现它甚至比 if 语句方式还要慢(这不一定是低效的,只是有一个弱点).
This creates an extra object, though, so it's really wasteful and I found it to be even slower than the if-statement way (which isn't necessarily inefficient, just has the one weakness).
推荐答案
你不能在 if 中使用布尔值.但这并不意味着在汇编级别会有分支.
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.
如果您检查该方法的编译代码(顺便说一下,使用 return b ? 1 : 0;
编译为完全相同的指令),您会发现它没有使用跳转:
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
注意:这是在热点服务器 7 上 - 您可能会在不同的 VM 上得到不同的结果.
Note: this is on hotspot server 7 - you might get different results on a different VM.
相关文章