-
Hi all, I am a newbie developer and I'd like to ask if there is any performance consideration when passing ref struct types to a function. The ref struct I am using is relatively large so I want to avoid value coping. It turns out that dot net supports passing a ref struct to a function by reference. On the other hand, I also noticed that the ref struct could be passed to a function by its pointer (in unsafe context). I guess these two approaches can both avoid value copying but I am not sure which one is more efficient? I would be also very appreciative if anyone would like to explain the internal mechanisms when passing a ref struct by reference and by pointer. Thank you for sharing your thoughts! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
The internal mechanism is the same. The code quality difference between the two are negligible. The main differences for ref structs is in safety guardrails. Passing by reference is safe concept. The C# compiler is going to report error if the code attempts to create a dangling pointer. For example, the following example is going to produce compiler error: ref int M(ref int x)
{
int x = 1;
return ref x;
} However, the equivalent code with unsafe context and pointers is going to compile fine, and it is likely going to crash at runtime due to the severe lifetime bug. |
Beta Was this translation helpful? Give feedback.
-
Ref structs are always on stack and can't be moved by GC. A pointer and a ref are expected to generate exactly same code. Ref gives you more safety around lifetime. |
Beta Was this translation helpful? Give feedback.
The internal mechanism is the same. The code quality difference between the two are negligible.
The main differences for ref structs is in safety guardrails. Passing by reference is safe concept. The C# compiler is going to report error if the code attempts to create a dangling pointer. For example, the following example is going to produce compiler error:
However, the equivalent code with unsafe context and pointers is going to compile fine, and it is likely going to crash at runtime due to the severe lifetime bug.