Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When ++counter occures, what happens in the memory?

Tags:

c#

c#-4.0

Lets suppose i have :

int counter;
++counter;

The question is : what happened in the memory (stack) ? If there is a new variable creates in stack and copy previous variable's value and add then +1 or its using temp variable, add there +1 and then places new value in counter ?

like image 958
Jviaches Avatar asked Dec 06 '25 04:12

Jviaches


2 Answers

The value of counter is loaded from memory into a CPU register, it is incremented, and then written back to that same memory address. No additional memory is allocated during this process, and it doesn't make a difference if counter lives in the stack or anywhere else.

like image 140
Jon Avatar answered Dec 08 '25 16:12

Jon


It depends, but usually nothing happens to memory. One of the most important jobs done by the jitter is to avoid using memory as much as possible. Particularly for local variables like yours. It stores the value of the variable in a CPU register instead. And the ++ operator simply produces an INC machine code instruction to increment the value in the register. Very fast, it takes 0 or 1 cpu cycle. With 0 being common because it can be executed in parallel with another instruction.

See this answer for a list of optimizations performed by the jitter.

like image 22
Hans Passant Avatar answered Dec 08 '25 17:12

Hans Passant