3

我在 C# 中使用一个数组,如下所示:

class abc 
{
    xyz x = new xyz(); // some other class
    public double [] arr = new double [100]; // Allocated 400 bytes 
                                             // for this array.
                                             // 100 is imaginary size 
                                             // shown here for simplicity.
                                             // Actual size will depend on input.
    private void something() 
    {
        x.funA(arr);
    }
}

abc上面的类中,数组消耗 400 个字节。现在,我在某个函数中将该数组作为参数传递给 class xyz

我的问题是是否会在 class 中分配新的 400 字节xyz。400 字节并不是什么大问题,但在我的程序中,我传递了一个占用 1 MB 的数组。

4

2 回答 2

2

存储引用所需的内存量。据我记得,在 32 位机器上是 8 个字节,在 64 位机器上是 12 个字节。

于 2012-07-11T05:46:53.230 回答
1

对于引用类型,在函数调用期间只有引用本身被压入堆栈。对于值类型,值本身被压入堆栈。

对象/数组/等都是引用类型,这意味着只有一个reference对象被压入堆栈以进行函数调用,实际对象本身将驻留在 GC 堆或进程分配动态内存的任何地方。引用的大小取决于体系结构,但在大多数现代系统上会在 32-64 位(4-8 字节)之间变化。

您可能需要阅读值和引用类型:

http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx

http://msdn.microsoft.com/en-us/library/490f96s2.aspx

这是 C# 的简单性可能有点违反直觉的时候之一。从 C++ 的角度来看更容易可视化:

double *data = new double[100]; //you can see here that "data" is merely a pointer to a double array with 100 elements, it doesn't actually hold the array itself.
somefunction(data); //now, it's more obvious what we're doing here: data is just a pointer, so all we're doing is passing a pointer to the function, not a double array.
于 2012-07-11T05:53:02.283 回答