哪个更快:if (bool) 或 if(int)?

2022-01-19 00:00:00 assembly boolean int c++

哪个值更好用?布尔真还是整数 1?

上面的题目让我在 if 条件下用 boolint 做了一些实验.所以出于好奇,我写了这个程序:

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.

    相关文章