c# - Does using "new" on a struct allocate it on the heap or stack?

ID : 10240

viewed : 46

Tags : c#.netmemory-managementc#

Top 5 Answer for c# - Does using "new" on a struct allocate it on the heap or stack?

vote vote


Okay, let's see if I can make this any clearer.

Firstly, Ash is right: the question is not about where value type variables are allocated. That's a different question - and one to which the answer isn't just "on the stack". It's more complicated than that (and made even more complicated by C# 2). I have an article on the topic and will expand on it if requested, but let's deal with just the new operator.

Secondly, all of this really depends on what level you're talking about. I'm looking at what the compiler does with the source code, in terms of the IL it creates. It's more than possible that the JIT compiler will do clever things in terms of optimising away quite a lot of "logical" allocation.

Thirdly, I'm ignoring generics, mostly because I don't actually know the answer, and partly because it would complicate things too much.

Finally, all of this is just with the current implementation. The C# spec doesn't specify much of this - it's effectively an implementation detail. There are those who believe that managed code developers really shouldn't care. I'm not sure I'd go that far, but it's worth imagining a world where in fact all local variables live on the heap - which would still conform with the spec.

There are two different situations with the new operator on value types: you can either call a parameterless constructor (e.g. new Guid()) or a parameterful constructor (e.g. new Guid(someString)). These generate significantly different IL. To understand why, you need to compare the C# and CLI specs: according to C#, all value types have a parameterless constructor. According to the CLI spec, no value types have parameterless constructors. (Fetch the constructors of a value type with reflection some time - you won't find a parameterless one.)

It makes sense for C# to treat the "initialize a value with zeroes" as a constructor, because it keeps the language consistent - you can think of new(...) as always calling a constructor. It makes sense for the CLI to think of it differently, as there's no real code to call - and certainly no type-specific code.

It also makes a difference what you're going to do with the value after you've initialized it. The IL used for

Guid localVariable = new Guid(someString); 

is different to the IL used for:

myInstanceOrStaticVariable = new Guid(someString); 

In addition, if the value is used as an intermediate value, e.g. an argument to a method call, things are slightly different again. To show all these differences, here's a short test program. It doesn't show the difference between static variables and instance variables: the IL would differ between stfld and stsfld, but that's all.

using System;  public class Test {     static Guid field;      static void Main() {}     static void MethodTakingGuid(Guid guid) {}       static void ParameterisedCtorAssignToField()     {         field = new Guid("");     }      static void ParameterisedCtorAssignToLocal()     {         Guid local = new Guid("");         // Force the value to be used         local.ToString();     }      static void ParameterisedCtorCallMethod()     {         MethodTakingGuid(new Guid(""));     }      static void ParameterlessCtorAssignToField()     {         field = new Guid();     }      static void ParameterlessCtorAssignToLocal()     {         Guid local = new Guid();         // Force the value to be used         local.ToString();     }      static void ParameterlessCtorCallMethod()     {         MethodTakingGuid(new Guid());     } } 

Here's the IL for the class, excluding irrelevant bits (such as nops):

.class public auto ansi beforefieldinit Test extends [mscorlib]System.Object     {     // Removed Test's constructor, Main, and MethodTakingGuid.      .method private hidebysig static void ParameterisedCtorAssignToField() cil managed     {         .maxstack 8         L_0001: ldstr ""         L_0006: newobj instance void [mscorlib]System.Guid::.ctor(string)         L_000b: stsfld valuetype [mscorlib]System.Guid Test::field         L_0010: ret          }      .method private hidebysig static void ParameterisedCtorAssignToLocal() cil managed     {         .maxstack 2         .locals init ([0] valuetype [mscorlib]System.Guid guid)             L_0001: ldloca.s guid             L_0003: ldstr ""             L_0008: call instance void [mscorlib]System.Guid::.ctor(string)             // Removed ToString() call         L_001c: ret     }      .method private hidebysig static void ParameterisedCtorCallMethod() cil  managed         {            .maxstack 8         L_0001: ldstr ""         L_0006: newobj instance void [mscorlib]System.Guid::.ctor(string)         L_000b: call void Test::MethodTakingGuid(valuetype [mscorlib]System.Guid)         L_0011: ret          }      .method private hidebysig static void ParameterlessCtorAssignToField() cil managed     {         .maxstack 8         L_0001: ldsflda valuetype [mscorlib]System.Guid Test::field         L_0006: initobj [mscorlib]System.Guid         L_000c: ret      }      .method private hidebysig static void ParameterlessCtorAssignToLocal() cil managed     {         .maxstack 1         .locals init ([0] valuetype [mscorlib]System.Guid guid)         L_0001: ldloca.s guid         L_0003: initobj [mscorlib]System.Guid         // Removed ToString() call         L_0017: ret      }      .method private hidebysig static void ParameterlessCtorCallMethod() cil managed     {         .maxstack 1         .locals init ([0] valuetype [mscorlib]System.Guid guid)             L_0001: ldloca.s guid         L_0003: initobj [mscorlib]System.Guid         L_0009: ldloc.0          L_000a: call void Test::MethodTakingGuid(valuetype [mscorlib]System.Guid)         L_0010: ret      }      .field private static valuetype [mscorlib]System.Guid field } 

As you can see, there are lots of different instructions used for calling the constructor:

  • newobj: Allocates the value on the stack, calls a parameterised constructor. Used for intermediate values, e.g. for assignment to a field or use as a method argument.
  • call instance: Uses an already-allocated storage location (whether on the stack or not). This is used in the code above for assigning to a local variable. If the same local variable is assigned a value several times using several new calls, it just initializes the data over the top of the old value - it doesn't allocate more stack space each time.
  • initobj: Uses an already-allocated storage location and just wipes the data. This is used for all our parameterless constructor calls, including those which assign to a local variable. For the method call, an intermediate local variable is effectively introduced, and its value wiped by initobj.

I hope this shows how complicated the topic is, while shining a bit of light on it at the same time. In some conceptual senses, every call to new allocates space on the stack - but as we've seen, that isn't what really happens even at the IL level. I'd like to highlight one particular case. Take this method:

void HowManyStackAllocations() {     Guid guid = new Guid();     // [...] Use guid     guid = new Guid(someBytes);     // [...] Use guid     guid = new Guid(someString);     // [...] Use guid } 

That "logically" has 4 stack allocations - one for the variable, and one for each of the three new calls - but in fact (for that specific code) the stack is only allocated once, and then the same storage location is reused.

EDIT: Just to be clear, this is only true in some cases... in particular, the value of guid won't be visible if the Guid constructor throws an exception, which is why the C# compiler is able to reuse the same stack slot. See Eric Lippert's blog post on value type construction for more details and a case where it doesn't apply.

I've learned a lot in writing this answer - please ask for clarification if any of it is unclear!

vote vote


The memory containing a struct's fields can be allocated on either the stack or the heap depending on the circumstances. If the struct-type variable is a local variable or parameter that is not captured by some anonymous delegate or iterator class, then it will be allocated on the stack. If the variable is part of some class, then it will be allocated within the class on the heap.

If the struct is allocated on the heap, then calling the new operator is not actually necessary to allocate the memory. The only purpose would be to set the field values according to whatever is in the constructor. If the constructor is not called, then all the fields will get their default values (0 or null).

Similarly for structs allocated on the stack, except that C# requires all local variables to be set to some value before they are used, so you have to call either a custom constructor or the default constructor (a constructor that takes no parameters is always available for structs).

vote vote


To put it compactly, new is a misnomer for structs, calling new simply calls the constructor. The only storage location for the struct is the location it is defined.

If it is a member variable it is stored directly in whatever it is defined in, if it is a local variable or parameter it is stored on the stack.

Contrast this to classes, which have a reference wherever the struct would have been stored in its entirety, while the reference points somewhere on the heap. (Member within, local/parameter on stack)

It may help to look a bit into C++, where there is not real distinction between class/struct. (There are similar names in the language, but they only refer to the default accessibility of things) When you call new you get a pointer to the heap location, while if you have a non-pointer reference it is stored directly on the stack or within the other object, ala structs in C#.

vote vote


As with all value types, structs always go where they were declared.

See this question here for more details on when to use structs. And this question here for some more info on structs.

Edit: I had mistankely answered that they ALWAYS go in the stack. This is incorrect.

vote vote


I'm probably missing something here but why do we care about allocation?

Value types are passed by value ;) and thus can't be mutated at a different scope than where they are defined. To be able to mutate the value you have to add the [ref] keyword.

Reference types are passed by reference and can be mutated.

There are of course immutable reference types strings being the most popular one.

Array layout/initialization: Value types -> zero memory [name,zip][name,zip] Reference types -> zero memory -> null [ref][ref]

Top 3 video Explaining c# - Does using "new" on a struct allocate it on the heap or stack?