Does an empty array in .NET use any space?

后端 未结 9 1545
暗喜
暗喜 2021-01-01 10:39

I have some code where I\'m returning an array of objects.

Here\'s a simplified example:

string[] GetTheStuff() {
    List s = null;
             


        
9条回答
  •  余生分开走
    2021-01-01 11:23

    I know this is old question, but it's a basic question and I needed a detailed answer.

    So I explored this and got results:

    In .Net when you create an array (for this example I use int[]) you take 6 bytes before any memory is allocated for your data.

    Consider this code [In a 32 bit application!]:

    int[] myArray = new int[0];
    int[] myArray2 = new int[1];
    char[] myArray3 = new char[0];
    

    And look at the memory:

    myArray:  a8 1a 8f 70 00 00 00 00 00 00 00 00
    myArray2: a8 1a 8f 70 01 00 00 00 00 00 00 00 00 00 00 00
    myArray3: 50 06 8f 70 00 00 00 00 00 00 00 00
    

    Lets explain that memory:

    • Looks like the first 2 bytes are some kind of metadata, as you can see it changes between int[] and char[] (a8 1a 8f 70 vs 50 06 8f 70)
    • Then it holds the size of the array in integer variable (little endian). so it's 00 00 00 00 for myArray and 01 00 00 00 for myArray2
    • Now it's our precious Data [I tested with Immediate Window]
    • After that we see a constant (00 00 00 00). I don't know what its meaning.

    Now I feel a lot better about zero length array, I know how it works =]

提交回复
热议问题