为...循环使用short而不是int的好处

Mat*_*s D 7 c++ loops for-loop

在for循环中使用short而不是int有什么好处吗?即

for(short j = 0; j < 5; j++) {
Run Code Online (Sandbox Code Playgroud)

我的99%的循环涉及3000以下的数字,所以我认为int会浪费字节.谢谢!

ham*_*mar 9

不可以.循环变量可能会被分配给一个寄存器,因此最终会占用相同的空间量.


Joh*_*hey 9

不,没有任何好处.无论如何,short可能会最终获得一个完整的寄存器(32位,一个int).

您也将失去在IDE中输入额外两个字母的小时数.(那只是个笑话).


Fre*_*ihl 5

查看生成的汇编程序代码,您可能会看到使用int生成更清晰的代码.

C代码:

#include <stdio.h>

int main(void) {
    int j;

    for(j = 0; j < 5; j++) {
        printf("%d", j);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用短:

 080483c4 <main>:
 80483c4:   55                      push   %ebp
 80483c5:   89 e5                   mov    %esp,%ebp
 80483c7:   83 e4 f0                and    $0xfffffff0,%esp
 80483ca:   83 ec 20                sub    $0x20,%esp
 80483cd:   66 c7 44 24 1e 00 00    movw   $0x0,0x1e(%esp)
 80483d4:   eb 1c                   jmp    80483f2 <main+0x2e>
 80483d6:   0f bf 54 24 1e          movswl 0x1e(%esp),%edx
 80483db:   b8 c0 84 04 08          mov    $0x80484c0,%eax
 80483e0:   89 54 24 04             mov    %edx,0x4(%esp)
 80483e4:   89 04 24                mov    %eax,(%esp)
 80483e7:   e8 08 ff ff ff          call   80482f4 <printf@plt>
 80483ec:   66 83 44 24 1e 01       addw   $0x1,0x1e(%esp)
 80483f2:   66 83 7c 24 1e 04       cmpw   $0x4,0x1e(%esp)
 80483f8:   7e dc                   jle    80483d6 <main+0x12>
 80483fa:   c9                      leave  
 80483fb:   c3                      ret    
Run Code Online (Sandbox Code Playgroud)

使用int:

 080483c4 <main>:
 80483c4:   55                      push   %ebp
 80483c5:   89 e5                   mov    %esp,%ebp
 80483c7:   83 e4 f0                and    $0xfffffff0,%esp
 80483ca:   83 ec 20                sub    $0x20,%esp
 80483cd:   c7 44 24 1c 00 00 00    movl   $0x0,0x1c(%esp)
 80483d4:   00 
 80483d5:   eb 1a                   jmp    80483f1 <main+0x2d>
 80483d7:   b8 c0 84 04 08          mov    $0x80484c0,%eax
 80483dc:   8b 54 24 1c             mov    0x1c(%esp),%edx
 80483e0:   89 54 24 04             mov    %edx,0x4(%esp)
 80483e4:   89 04 24                mov    %eax,(%esp)
 80483e7:   e8 08 ff ff ff          call   80482f4 <printf@plt>
 80483ec:   83 44 24 1c 01          addl   $0x1,0x1c(%esp)
 80483f1:   83 7c 24 1c 04          cmpl   $0x4,0x1c(%esp)
 80483f6:   7e df                   jle    80483d7 <main+0x13>
 80483f8:   c9                      leave  
 80483f9:   c3                      ret    
Run Code Online (Sandbox Code Playgroud)


Nem*_*vic 0

没有。无论如何,您的计数器很可能最终会出现在寄存器中,并且它们通常至少与 int 大小相同