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.
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
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:
上一篇: 性能:方法应该返回一个类或结构?
下一篇: 数组内存分配说明