如果可以的话,我们应该总是 return by ref 吗?

Should we always return by ref if we can?

现在使用 C# 7,我们可以 return by ref with return ref。根据我收集到的信息,引用是 32 位或 64 位。现在,如果我有一个带有 long Xlong Y 的结构 Coord,那将是 128 位,所以 return 坐标会更容易,(以及通过引用传递它)以避免复制 128 位。

另一方面,如果我尝试 return ref 一个只有 8 位的 byte,对它的引用将比复制字节本身大得多,对吗?

所以,我的主要问题是:如果我们想要 return 的对象可以 return 由 ref 编辑(即,不是局部变量)并且它的大小大于引用的大小,我们应该 return by ref?

编辑: 快速代码示例

// This size is 128 bytes, which is 2 or 4x larger than the size of a reference
public struct Coord                                 
{
    public long X, Y;
}

private Coord myCoord;

// This will return the Coord by value, meaning copying the full 128 bytes
public Coord GetCoordValue() => myCoord;          

// This will return the Coord by reference, meaning copying only 32 or 64 bytes
public ref readonly Coord GetCoordRef() => ref myCoord;      

此外,这个特殊的结构非常简单,它已经比 return 小 2/4 倍 ref

编辑2:我做了GetCoordRef()readonly这样调用者就不能保存和改变myCoord的值,从而保留封装,尽管我认为默认使用它仍然不明智。

If the object we want to return can be returned by ref (ie, not a local variable) and its size is larger than the size of a reference, should we return by ref?

(1) 号

(2) 仅适用于高级用户:是的,正是在您的经验、准确的分析数据表明进行此更改会将您的程序从令用户失望的程序转变为令用户满意的程序的情况下

市场上是否有程序的失败或成功可以追溯到复制几个额外字节的几纳秒差异被交易为稍后进行指针间接的几纳秒?我不知道有什么,但也许你编写的程序的用户对他们希望 API 占用的纳秒数的预算非常紧张。