Static value field heaped in C #?

Just out of curiosity - consider the following example:

public class A { public static int Foo; } public class Program { static void Main() { // The following variable will be allocated on the // stack and will directly hold 42 because it is a // value type. int foo = 42; // The following field resides on the (high frequency) // heap, but is it boxed because of being a value type? A.Foo = 42; } } 

My question is: is the Foo field in the field because it is on the heap? Or is it in a special container / memory object section that encapsulates it in the same way that an instance value type field is part of the object on the heap?

I would suggest that it is not in the box, but I do not know for sure, and I can not find any documentation on it.

Thank you for your help.

+5
source share
2 answers

The CLR has no restrictions that each class field must have the same storage type. Only instance members fall into the GC heap. Static elements are allocated on the bootloader heap. Or in streaming local storage when the field has the [ThreadStatic] attribute. This, of course, imposes a contract on the fact that the static member is shared by each instance of the class object.

A very simple btw implementation, jitter allocates storage and knows the address of the field. Thus, any load and stores directly use the address of the variable. No extra dereferencing pointers, very effective.

So, no, there is no need for a box at all, a static int will only take 4 bytes.

If you want to see this for yourself, use the Debug + Windows + Disassembly window. Shows the machine code, you will see it using the address of the variable directly. This will be a different address each time you run a program that is against the law.

+5
source

Since Sriram and Lee gave the answer in the comments on this question, but did not give an answer, I will summarize:

No, the value does not fit in the box. Value types can be on the heap, they are only in the box when they are used as a reference type.

You can also see that there is no box in the IL code of my example.

 .method private hidebysig static void Main() cil managed { .entrypoint // Code size 12 (0xc) .maxstack 1 .locals init ([0] int32 foo) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: ldc.i4.s 42 IL_0006: stsfld int32 StaticValueTypeFieldBoxing.A::Foo IL_000b: ret } // end of method Program::Main 
+2
source

Source: https://habr.com/ru/post/1202138/


All Articles