Difference between declaring variables before or in loop?

前端 未结 25 2122
长发绾君心
长发绾君心 2020-11-22 02:37

I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (q

25条回答
  •  别那么骄傲
    2020-11-22 03:25

    I made a simple test:

    int b;
    for (int i = 0; i < 10; i++) {
        b = i;
    }
    

    vs

    for (int i = 0; i < 10; i++) {
        int b = i;
    }
    

    I compiled these codes with gcc - 5.2.0. And then I disassembled the main () of these two codes and that's the result:

    1º:

       0x00000000004004b6 <+0>:     push   rbp
       0x00000000004004b7 <+1>:     mov    rbp,rsp
       0x00000000004004ba <+4>:     mov    DWORD PTR [rbp-0x4],0x0
       0x00000000004004c1 <+11>:    jmp    0x4004cd 
       0x00000000004004c3 <+13>:    mov    eax,DWORD PTR [rbp-0x4]
       0x00000000004004c6 <+16>:    mov    DWORD PTR [rbp-0x8],eax
       0x00000000004004c9 <+19>:    add    DWORD PTR [rbp-0x4],0x1
       0x00000000004004cd <+23>:    cmp    DWORD PTR [rbp-0x4],0x9
       0x00000000004004d1 <+27>:    jle    0x4004c3 
       0x00000000004004d3 <+29>:    mov    eax,0x0
       0x00000000004004d8 <+34>:    pop    rbp
       0x00000000004004d9 <+35>:    ret
    

    vs

       0x00000000004004b6 <+0>: push   rbp
       0x00000000004004b7 <+1>: mov    rbp,rsp
       0x00000000004004ba <+4>: mov    DWORD PTR [rbp-0x4],0x0
       0x00000000004004c1 <+11>:    jmp    0x4004cd 
       0x00000000004004c3 <+13>:    mov    eax,DWORD PTR [rbp-0x4]
       0x00000000004004c6 <+16>:    mov    DWORD PTR [rbp-0x8],eax
       0x00000000004004c9 <+19>:    add    DWORD PTR [rbp-0x4],0x1
       0x00000000004004cd <+23>:    cmp    DWORD PTR [rbp-0x4],0x9
       0x00000000004004d1 <+27>:    jle    0x4004c3 
       0x00000000004004d3 <+29>:    mov    eax,0x0
       0x00000000004004d8 <+34>:    pop    rbp
       0x00000000004004d9 <+35>:    ret 
    

    Which are exaclty the same asm result. isn't a proof that the two codes produce the same thing?

提交回复
热议问题