Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# out parameter when return value is void

Tags:

c#

struct

xna

Is there any benefit to this XNA method to multiply two matrices?

public static void Multiply (
     ref Matrix matrix1,
     ref Matrix matrix2,
     out Matrix result
)

Why is the result an out parameter rather than returned? Is there any speed or memory benefit over using a simple return value? Considering that Matrix is a struct, does that have anything to do with it? I can understand why matrix1 and matrix2 are ref variables, so it doesn't have to copy them, but I don't get why the third is an out parameter instead of a return or ref variable.

like image 677
Ed Marty Avatar asked Dec 09 '22 09:12

Ed Marty


1 Answers

Yes, an important one. The Matrix type violates one of the guidelines of .NET programming, a struct shouldn't be larger than 16 bytes. Typically 4 int fields. Matrix has 16 float fields, 64 bytes total.

The 16-byte recommendation is relevant to the way structures as passed to/from a method in the generated machine code. Even the x86 core, one that's particularly starved for CPU registers, has enough registers to allow the structure to be stored in CPU registers instead of the stack frame. However, if it doesn't fit then the structure is passed through the stack frame. And gets copied both when calling and receiving. That's expensive. Same applies to the return value.

The workaround for this expense is to pass the structure value by ref or out. Just like the Multiply method does. Now it only requires passing a pointer to the structure, 4 bytes on a 32-bit core. With the overhead of having to dereference the pointer every time the code uses a field of the structure. Which is okay, that's needed on a class object as well.

like image 149
Hans Passant Avatar answered Dec 12 '22 00:12

Hans Passant