开发者

C# out parameter when return value is void

Is there any benefit to this XNA method to multiply two ma开发者_运维技巧trices?

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.


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.


Arguably for the same reason: so that it doesn't have to be copied (since it's a value type). However, I don't know if the compiler can elide this copy and under what circumstances -- if it can, then this is already an ugly way of doing things that doesn't buy you anything.

Also keep in mind that mutable value types give off a bad smell to begin with.


Yes there is a performance benefit. Performance is better considering it's a value type, and making it an out parameter allows it to be marshaled from the callee back to the caller.

Check out the remarks for the OutAttribute and Blittable and Non-Blittable types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜