Which is faster : if (bool) or if(int)?(哪个更快:if (bool) 或 if(int)?)
问题描述
哪个值更好用?布尔真还是整数 1?
上面的题目让我在 if 条件下用 bool 和 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为每个函数生成asm代码如下:
g++ intbool.cpp -S generates asm code for each functions as follows:
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
g(bool)
__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
令人惊讶的是,g(bool) 生成了更多 asm 指令!这是否意味着 if(bool) 比 if(int) 慢一点?我曾经认为 bool 是专门设计用于 if 等条件语句的,所以我期望 g(bool) 生成较少asm 指令,从而使 g(bool) 更加高效和快速.
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.
到目前为止,我没有使用任何优化标志.但即使没有它,为什么它会为 g(bool) 生成更多的 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.
推荐答案
对我来说很有意义.您的编译器显然将 bool 定义为 8 位值,并且您的系统 ABI 要求它在将小(<32 位)整数参数推送到调用时将其提升"为 32 位堆.因此,为了比较 bool,编译器生成代码以隔离 g 接收到的 32 位参数的最低有效字节,并将其与 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.
这篇关于哪个更快:if (bool) 或 if(int)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:哪个更快:if (bool) 或 if(int)?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
