性能建议中的可空类型装箱

Nullable types boxing in performance recommendations

摘自Unity perfomance documentation

Example of problematic boxing via nullable value types

This code demonstrates a dummy particle class that one may create in a Unity project. A call to TryGetSpeed() will cause object allocation on the heap which will need to be garbage collected at a later point in time. This example is particularly problematic as there may be 1000+ or many more particles in a scene, each being asked for their current speed. Thus, 1000's of objects would be allocated and consequently de-allocated every frame, which would greatly diminish performance. Re-writing the function to return a negative value such as -1 to indicate a failure would avoid this issue and keep memory on the stack.

public class MyParticle
{
   // Example of function returning nullable value type
   public int? TryGetSpeed()
   {
       // Returns current speed int value or null if fails
   }
}

这是正确的吗?

应该在堆栈中分配局部值类型(如果它不在匿名方法或迭代器块中)。为什么如果 return 一个可为空的值类型,这将在堆中分配?

为什么我要在堆栈上保留内存 returning 一个值类型?

Is this correct?

不,这不正确。 int?Nullable<int> 相同,它仍然是一个值类型,并且仍然是从方法返回的,没有堆分配,没有装箱。

Microsoft 似乎已经注意到文档中的这个错误段落,因为它已被删除。 Here's a cached version of the page,包括段落。

我假设此更改是最近发生的,因为我进一步假设当您将 link 发布到文档页面时,它实际上确实包含了该段落,因此问题本身。但该页面现在肯定 包含该段落。事实上,there was an issue opened on Github concerning this exact passage, and that issue was closed (so, presumably fixed) two hours ago (midday on November 7, 2020,太平洋标准时间)。

也就是说,请注意:the stack is an implementation detail。使用值类型可以(在这种情况下)避免在堆上分配的需要,但在其他情况下值类型可以并且确实存在于堆上,因此如果有人关心堆分配与堆栈分配,则需要根据自己的除了严格的价值与参考类型问题之外的其他事情的预测。