Extracted from 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 } }
Is this correct?
A local value type should be allocate in the stack (if it is not in an anonymous method or an iterator block). Why if return a nullable value type, this will be allocate in the heap?
And why am I going to keep memory on the stack returning a value type?