Array memory Allocation clarification

Today i was reading a SO thread about array and its memory allocation. And i found an answer which was neatly explained and i must say its excellent.

But after reading that answer, i got few more questions which i kept asking myself about what i just read. So far still i am unable to answer it myself nor able to google it up. Hence i require your kind help in explaining those questions to me.

  • Why is array getting created on heap when every of its content is getting stored on stack? Just 2 avoid boxing in case of value types?
  • If above was true, then why array had 2 be created on heap first of all?

  • When he said in his answer new int[100] is actually getting created on heap, is 400 (100 * 4) bytes getting allocated on heap? If so, why? because all the values are getting stored on stack

  • If 1000 item array is created, then how on earth stack is enough to be stored? I know 1 MB is the size of the stack allocated. but in this case it will exceed. So whats the funda??
  • Please feel free to add your own questions or more info if you may have to this.

    Thanks


    When we say array is allocated on heap it means the values will be in heap. Array values are not stored on stack. I think this answers all 3 questions.

    var myArray = new int[10];
    

    Above line creates myArray variable on stack but the memory of array is allocated on heap and so all values stored in it also go in heap.


    From what I understand, in a non-formal definition, value types are stored locally to where they are defined. So if a single value type is defined in a method, it will be stored on the stack. If it's defined as field on a class, or in this case, as items in an array, then the 'parent' object is on the heap so the value type will also be stored on the heap.

    UPDATE

    For more details on value types versus reference types and the stack, check out Eric Lippert's articles:

  • The Stack Is An Implementation Detail, Part One
  • The Stack Is An Implementation Detail, Part Two
  • 链接地址: http://www.djcxy.com/p/78900.html

    上一篇: 性能:方法应该返回一个类或结构?

    下一篇: 数组内存分配说明