如果数组用作struct(C#)中的元素,它存储在哪里?

sha*_*sha 5 c# arrays heap stack struct

我们尽可能在C#中使用struct主要是因为它存储在堆栈中并且没有为它创建对象.这提升了性能.

另一方面,数组存储在堆上.

我的问题是,如果我将数组包含为结构的元素,则如下所示:

struct MotionVector
{
    int[] a;
    int b;
}
Run Code Online (Sandbox Code Playgroud)

那会是什么后果.该数组是否会存储在堆栈中?或者使用struct的性能优势会丢失?

Dhw*_*hah 8

只有指向数组的指针才会存储在堆栈中.实际的数组将存储在堆中.


Mic*_*ers 0

如果您不想动态创建元素,请考虑在启动期间创建 MotionVector 实例的(大)缓冲区,并在需要时重用这些缓冲区。那么你就不会受到动态创建/销毁它们的惩罚。

当然,您必须编写一些小函数来获取“免费”实例,并在结构中使用布尔值(或通过使用接口)来获取实例。

为此,您可以例如:

在应用程序初始化期间创建运动向量:

MotionVectors motionVectors;
Run Code Online (Sandbox Code Playgroud)

将布尔值添加到 MotionVector 类:

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

    public MotionVector() 
    {
        InUse = false; 
    }
}
Run Code Online (Sandbox Code Playgroud)

定义新类 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];
    }
}
Run Code Online (Sandbox Code Playgroud)