这是更快:若(布尔)或(INT)? [英] Which is faster : if (bool) or if(int)?
问题描述
<一个href=\"http://stackoverflow.com/questions/5554725/which-value-is-better-to-use-boolean-true-or-integer-1\">Which值是更好地使用?布尔真或整数1?
上面的话题让我做一些实验用布尔
,如果 INT
在
状态。所以,只是出于好奇,我写了这个程序:
The above topic made me do some experiments with bool
and int
in if
condition. So just out of curiosity I wrote this program:
int f(int i)
{
if ( i ) return 99; //if(int)
else return -99;
}
int g(bool b)
{
if ( b ) return 99; //if(bool)
else return -99;
}
int main(){}
G ++ intbool.cpp -S
生成汇编code每个功能如下:
g++ intbool.cpp -S
generates asm code for each functions as follows:
-
ASM code为
F(INT)
__Z1fi:
LFB0:
pushl %ebp
LCFI0:
movl %esp, %ebp
LCFI1:
cmpl $0, 8(%ebp)
je L2
movl $99, %eax
jmp L3
L2:
movl $-99, %eax
L3:
leave
LCFI2:
ret
ASM code为克(布尔)
__Z1gb:
LFB1:
pushl %ebp
LCFI3:
movl %esp, %ebp
LCFI4:
subl $4, %esp
LCFI5:
movl 8(%ebp), %eax
movb %al, -4(%ebp)
cmpb $0, -4(%ebp)
je L5
movl $99, %eax
jmp L6
L5:
movl $-99, %eax
L6:
leave
LCFI6:
ret
出人意料的是,克(布尔)
产生更多的 ASM
的说明!这是否意味着如果(布尔)
是,如果不是慢一点(INT)
?我曾经以为布尔
特别设计的条件语句中使用,如如果
,所以我期待克(布尔)
来产生更少的汇编指令,从而使克(布尔)
更高效和快速。
Surprisingly, g(bool)
generates more asm
instructions! Does it mean that if(bool)
is little slower than if(int)
? I used to think bool
is especially designed to be used in conditional statement such as if
, so I was expecting g(bool)
to generate less asm instructions, thereby making g(bool)
more efficient and fast.
编辑:
我不使用任何优化的标志,截至目前。但即使没有它,为什么它生成克(布尔)更ASM
是我正在寻找一个合理的答案的问题。我还要告诉你, -O2
优化标志将产生完全相同ASM。但是,这不是问题。现在的问题是我问过。
I'm not using any optimization flag as of now. But even absence of it, why does it generate more asm for g(bool)
is a question for which I'm looking for a reasonable answer. I should also tell you that -O2
optimization flag generates exactly same asm. But that isn't the question. The question is what I've asked.
推荐答案
对我来说很有意义。编译器显然定义了一个布尔
作为一个8位的值,并在系统ABI需要它来促进小(小于32位)整数参数为32位他们推到时调用堆栈。因此,要比较一个布尔
,编译器生成code,以使得G接收32位参数的最低显著字节隔离,并与<$ C $比较C> CMPB 。在第一个例子中, INT
参数使用被压入堆栈,完整的32位,所以它只是比较对整个事情与 CMPL
。
Makes sense to me. Your compiler apparently defines a bool
as an 8-bit value, and your system ABI requires it to "promote" small (< 32-bit) integer arguments to 32-bit when pushing them onto the call stack. So to compare a bool
, the compiler generates code to isolate the least significant byte of the 32-bit argument that g receives, and compares it with cmpb
. In the first example, the int
argument uses the full 32 bits that were pushed onto the stack, so it simply compares against the whole thing with cmpl
.
这篇关于这是更快:若(布尔)或(INT)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!