3

假设我有:

int counter;
++counter;

问题是:内存(堆栈)中发生了什么?如果在堆栈中创建了一个新变量并复制前一个变量的值,然后添加 +1 或其使用的临时变量,添加 +1 然后将新值放入计数器?

4

5 回答 5

7

的值counter从内存加载到 CPU 寄存器中,递增,然后写回相同的内存地址。counter在这个过程中没有分配额外的内存,如果它位于堆栈或其他任何地方,它并没有什么区别。

于 2012-10-11T11:39:48.140 回答
3

这取决于,但通常不会对内存产生任何影响。抖动所做的最重要的工作之一是尽可能避免使用内存。特别是对于像你这样的局部变量。而是将变量的值存储在 CPU 寄存器中。并且 ++ 运算符只是产生一个 INC 机器代码指令来增加寄存器中的值。非常快,它需要 0 或 1 个 cpu 周期。0 很常见,因为它可以与另一条指令并行执行。

有关抖动执行的优化列表,请参阅此答案。

于 2012-10-11T11:52:13.260 回答
1

.Net first compiles to an intermediate language (IL).

The follogin .Net C# code

private void Form1_Load(object sender, EventArgs e)
{
    int i = 0;
    i++;
    int j = 0;
    ++j;
}

Compiles to IL code, viewed in a disassembler:

ldc.i4.0    //ldc = load constant on evaluation stack
stloc.0 //Store on top of the evaluation stack
ldloc.0 //Load a local variable
ldc.i4.1 //ldc = load constant on evaluation stack
add //add
stloc.0 //Store on local evaluation stack

ldc.i4.0 //Load contant 0 on the evaluation stack
stloc.1 //Store this on variable location 1
ldloc.1 //Load variable location 1
ldc.i4.1 //Load constant 1 on evaluation stack
add //Add 
stloc.1 //Store on evaluation stack

You can see that it does not matter in this case. It both compiles the same way. First load the value on the stack, store in the variable. then load value 1 on the stack, then add and save it in the variable.

I am not sure how this will finally compile to CPU instructions.

于 2012-10-11T12:52:20.980 回答
0

++counter 将递增 counter 并返回新的递增值。counter++ 将递增 counter 并返回递增前的值。

于 2012-10-11T11:40:31.520 回答
0

这是乔恩回答的补充。

在变量之前和变量之后使用 ++ 运算符时有一个区别。考虑下面的例子:

        int[] arr = { 1, 2, 3 };
        int counter = 0;

        Console.WriteLine(arr[counter++]);
        Console.WriteLine(arr[++counter]);

counter++打印 1++counter并将打印 3。

于 2012-10-11T11:54:59.000 回答