Christian Gollhardt Christian Gollhardt -3 years ago 46
C# Question

What does it mean to have a literal in an condition for memory?

Given the following example:

//this gets allocated
var foo = 42;

//what happens to 0?
if (foo > 0)
{
}


Out of curiostiy, what happens to the
0
in terms of memory consumption/instructions?

I always thought it is some instruction which is fired to the processor and forget. Nothing that needs to be stored in RAM (As long it is a literal and not a reference).

After taking part of this discussion I am a litte bit confused.

Does the
0
allocated in memory in some way? Does it need to be garbage collected? Is there a type of literal that could change the situation?

What happens under the hood?

Answer Source
//this gets allocated
var foo = 42;

"allocated" is not really the right word; that's a value-type local on the stack; it isn't an "allocation" as such. It is just ldc.i4 42, stloc.0.

//what happens to 0?
if (foo > 0)
{
}

Again, this isn't an allocation; there is nothing to collect; this is just ldloc.0, ldc.i4.0, cgt, brfalse.s. No allocations. Everything here is just values on the stack. GC refers to the managed heap, i.e. objects.

In terms of implementation : entering the method reserves a known amount of space on the stack (calculated by the compiler). Leaving the method does nothing - it leaves that memory untouched and just subtracts that same number back from the in use stack space.

So 0 is stored on the stack the same way as foo?

Not quite the same way; foo is a local, 0 is a transient. Basically locals come first, then the transient stack space starts after the locals. The transient stack space is used (at least in theory - the JIT may enregister it) for in-progress operations, including loading literal values. The transient area is only informally defined (the JIT understands it, but it isn't formally declared) - and only lasts for the duration of individual operations. Locals are per method scope.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download