C # out parameter when return value is invalid

Is there any use for this XNA Method to multiply two matrices?

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

Why is the result, not the return parameter, out? Is there any memory speed or advantage when using a simple return value? Given that Matrix is ​​a structure, does this have anything to do with it? I can understand why matrix1 and matrix2 are ref variables, so I don’t need to copy them, but I don’t understand why the third parameter is out instead of the variable return or ref.

+4
source share
3 answers

Yes, important. Matrix type violates one of the principles of .NET programming, the structure should not exceed 16 bytes. Usually 4 fields int. Matrix has 16 floating point fields, a total of 64 bytes.

The 16-byte recommendation relates to methods that are passed to / from the method in the generated machine code. Even the x86 core, which is especially starving for processor registers, has enough registers to allow the structure to store in processor registers instead of a stack frame. However, if it does not fit, the structure is passed through the stack stack. And it is copied both when calling and when receiving. It is expensive. The same applies to the return value.

The workaround for this expense is to pass the value of the structure through ref or out. Like the Multiply method. Now you only need to pass a pointer to the structure, 4 bytes per 32-bit kernel. With the overhead of having to dereference a pointer every time the code uses a structure field. What is good, what is needed for a class object.

+7
source

Perhaps for the same reason: so it does not need to be copied (since it is a value type). However, I don’t know if the compiler can handle this copy and under what circumstances - if possible, then this is an ugly way to do something that doesn’t buy anything.

Also keep in mind that mutable value types give an unpleasant odor to start with .

+4
source

Yes, there is a performance advantage. Performance better takes into account the type of value and makes it an output parameter that allows it to march from the called party back to the calling party.

Mark the notes for OutAttribute and Blittable and Non-Selected Types .

+3
source

Source: https://habr.com/ru/post/1346359/


All Articles