0

When we initialize a value type by using new keyword like:-

int i=new int();

Then what happens with memory allocation of this object. Is memory allocated on the stack or on the heap ?

Puneet Pant
  • 918
  • 12
  • 37
  • That depends on the variable. If it's a local variable in a regular method, it's all on the stack. If it's a field in a class, it's on the heap. But that code is precisely equivalent to `int i = 0;` - the use of `new` doesn't mean "Create a new object on the heap". (I'm sure this is a dupe, but I don't have time right now to find it - hence the quick "not a full answer" comment.) – Jon Skeet Apr 29 '18 at 06:44
  • Whether its on the stack or the heap is just an Implementation detail, and this horse left the stable a long time ago, meaning, the CLR chooses the most optimal way of allocating a variable, and in some cases it depends on several factors and sometimes not obvious. Second-guessing the compiler is actually less productive than profiling your code and writing better algorithms for performance – TheGeneral Apr 29 '18 at 06:51

2 Answers2

3

It depends on where this statement is written. If it's in the body of a method, the value will be allocated on the stack:

void Method()
{
    int i = new int(); // Allocated on stack
}

IL-Code:

ldc.i4.0
stloc.0    // store as local variable

If you write it in the body of a class, it will be allocated on the heap, as every reference type is allocated on the heap:

class Class
{
    int i = new int(); // Allocated on heap
}

IL-Code:

ldc.i4.0
stfld      int32 Class::i  // store in field

The same applies for initializing fields in a method or constructor of a class. For structs, it depends on where they are currently allocated.

adjan
  • 13,371
  • 2
  • 31
  • 48
1

It is being allocated on the stack.

Take a look at the IL in the following answer: Where and why use int a=new int?

int A = new int() compiles to:

IL_0001:  ldc.i4.0         // Push 0 onto the stack as int32.   
IL_0002:  stloc.0          // Pop a value from stack into local variable

int C = 100 compiles to:

IL_0005:  ldc.i4.s   100   // Push num onto the stack as int32
IL_0007:  stloc.2          // Pop a value from stack into local variable

There is basically no difference between them.

You can use this as a reference:

https://en.wikipedia.org/wiki/List_of_CIL_instructions

Update: As @Adrian wrote, it depends on the scope. There is not difference between int a = 10 and int a = new int() but it wasn't exactly the question.

ayun12
  • 479
  • 1
  • 4
  • 9
  • this answer is wrong, `int A = new int()` compiles to something completely different if its written as a class field – adjan Apr 29 '18 at 08:38