If an array is used as an element in struct (C#) , where is it stored?

We use struct in C# whenever possible mainly because it is stored on the stack and no objects are created for it. This boosts the performance.

On the other hand, arrays are stored on the heap.

My question is, if I include an array as an element of the struct, something as follows:

struct MotionVector
{
    int[] a;
    int b;
}

Then what will be the consequences. Will that array be stored on stack? Or the performance advantage of using struct will be lost?


If you don't want to create elements dynamically, consider to create a (big) buffer of MotionVector instances during startup and reuse those when needed. Then you will not get the penalty of creating/destructing them dynammically.

Of course you have to write some small functions to get a 'free' instance and to obtain one, use a boolean in the struct for that (or by using an interface).

To do this you could eg:

Create during initialisation of your app the motionvectors:

MotionVectors motionVectors;

Add a boolean to the MotionVector class:

public class MotionVector
{
    bool InUse { get; set; }

    public MotionVector() 
    {
        InUse = false; 
    }
}

Define the new class MotionVectors:

class MotionVectors
{
    MotionVector _instances[100];

    public void Free(MotionVector vector)
    {
        var index = 'search vector in _instances' 
        _instances[index].Inuse = false;
    }

    public MotionVector GetNewInstance()
    {
        var index = 'first free vector in _instances'
        _instances[index].Inuse = true;
        return _instances[index];
    }
}

Only the pointer to the array will be stored in the stack. The actual array will be stored in the heap.


int[] a is a reference type ie it references an array of integers. The 'reference' itself will be stored on the stack. However, the data it references will be stored on the heap when you do something like this:

MotionVector z;
z.a = new int[10];
链接地址: http://www.djcxy.com/p/78896.html

上一篇: 在C#堆中是否装有静态值类型的字段?

下一篇: 如果一个数组被用作struct(C#)中的一个元素,它在哪里存储?