views:

356

answers:

2

For instance, in VB.NET:

  Dim strArray(5) As String

As I understand it, because this is an array, the computer will allocate contiguous memory locations for each of the 5 elements. But how much space is allocated for each of the five elements? What if I decide to put a 5MB block of text in position 2 of the array?

Is it different for value types (e.g., an array of Int32)? I would think if it had to resize the block of memory for an individual element it would have to create a whole new array to preserve the contiguous memory feature.

+4  A: 

If you make an array of a reference type, I think only the references are kept in the variable. That is:

Dim strArray(5) As String

Will only actually be 6 references big with something like 4 bytes per reference (not sure on that).

The actual data will be stored (probably) on the heap.

This doesn't mean that changing a string's length is trivial, though--they must still be reallocated each time they are changed.

Michael Haren
Seems about right, (and I think it is 5)...
Arjan Einbu
It seems to be 6 as the array is zero indexed
Michael Haren
Nope, it's 6--in VB, you declare the *upper bound*, not the count." And it's always zero-based.
RolandTumble
Right. I never liked how VB has you declare the upper bound.
vg1890
+3  A: 

In .NET:

  • Arrays are usually stored on the heap (unless you use something like stackalloc in C#)
  • If you create an array of reference type values (e.g. strings) the array only contains the references
  • A reference is 4 bytes when running the 32-bit CLR, and 8 bytes when running the 64-bit CLR
  • Although the array itself is contiguous in memory, there's nothing to say that the strings themselves will be contiguous

So in your case, the array object itself will be

normal object overhead 
+ 4 bytes for the length (IIRC) 
+ (4 or 8 bytes per element) * 6 elements

The references within the array may refer to any string anywhere in memory, or Nothing.

For value types, the array holds the value directly - so an array of Int32s will take up:

normal object overhead
+ 4 bytes for the length
+ 4 bytes per element

An array of Int64s will take:

normal object overhead
+ 4 bytes for the length
+ 8 bytes per element

(etc). Booleans take up a byte per element, despite logically only being a single bit.

Jon Skeet