在循环内部或外部声明变量,它会产生很大的不同吗?

时间:2017-11-13 05:52:56

标签: c performance variable-declaration

例如

int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}

while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}

它在性能方面有很大差异吗?

6 个答案:

答案 0 :(得分:3)

是。变量i的范围在两种情况下都不同。

在第一种情况下,在块或函数中声明的变量i。因此,您可以在块或函数中访问它。

在第二种情况下,我在while循环中声明了一个变量。因此,您只能在while循环中访问它。

  

它在性能方面有很大差异吗?

,在声明它的情况下,在性能方面无关紧要。

对于示例1:

int main()
{
    int i, bigNumber;

    while(bigNumber--) {
        i = 0;
    }
}

<强>装配

main:
  push rbp
  mov rbp, rsp
.L3:
  mov eax, DWORD PTR [rbp-4]
  lea edx, [rax-1]
  mov DWORD PTR [rbp-4], edx
  test eax, eax
  setne al
  test al, al
  je .L2
  mov DWORD PTR [rbp-8], 0
  jmp .L3
.L2:
  mov eax, 0
  pop rbp
  ret

示例2:

int main()
{
    int bigNumber;

    while(bigNumber--) {
        int i;
        i = 0;
    }
}

<强>装配

main:
  push rbp
  mov rbp, rsp
.L3:
  mov eax, DWORD PTR [rbp-4]
  lea edx, [rax-1]
  mov DWORD PTR [rbp-4], edx
  test eax, eax
  setne al
  test al, al
  je .L2
  mov DWORD PTR [rbp-8], 0
  jmp .L3
.L2:
  mov eax, 0
  pop rbp
  ret

两者都生成相同的汇编代码。

答案 1 :(得分:0)

它有所不同......当你在循环外声明一个变量时,你可以在循环结束后得到它的值,但是如果你在循环中声明它,你就不能在循环之后使用它,因为它没有被定义< / p>

答案 2 :(得分:0)

问。这在性能方面有很大差异吗?

A。根本没有性能差异。唯一的区别是变量的范围是否在循环外可见。

答案 3 :(得分:0)

Computational complexity and I/O operations are most valuable things that you must considered as performance bottleneck in the programs. There is no performance difference between these two codes. Moreover, compilers do some optimization on codes and it is not unexpected if this two codes run as the same(i.e compiler convert second code to first automatically).

答案 4 :(得分:0)

The only difference I can see in assembly results is the location of a movl $0, -4(%rbp) instruction. In theory there may be a performance penalty for codes that use data which is spread more widely among memory (that will make your code less cache-friendly in theory)

In practise there will be no difference. Cache is big enough, Optimization will make both codes generate the same assembly, and most probably the code will be re-ordered. Following is a simple test case with all optimizations turned off and on.

Assembly results:

Assembly results

Code: Simple test case

Turning on optimizers will generate exact same result: Optimization on

答案 5 :(得分:0)

我认为如果你这样说,它会不断重新声明变量,所以无论你初始化什么,它都会在变量重新声明后丢失。

while(bigNumber--) {
   int i, a, b, c; 
   i = doSomething();
}