C# is there a difference between passing a struct

2019-08-23 08:53发布

问题:

As seen here, structs are passed by copy and classes by reference. But why is passing a struct by reference using the ref keyword still slower than passing a reference to a class ?

I got different speeds for my program by replacing the struct keywords with class. All of the variables were already passed with the ref keyword.
By changing keywords, I got 20% speed increase in my tests. Shoudn't the speed remain the same since I was already passing by reference ? What am I not understanding ?

回答1:

Passing struct by ref is roughly the same as passing class by value (pointer to data), passing class by ref (pointer to pointer to data) should be a bit slower than passing class by value as extra dereference required.

Whether you get speed improvements or not from replacing "pass struct by value" to "pass struct by ref" depends on size of struct. If you follow Microsoft's guidance "size of struct <= 16 bytes" the difference will likely be insignificant anyway, otherwise if struct is huge you likely see some performance gains.

The potential gains/losses also depend on 32bit vs. 64bit (x86/x64) CPU architecture choice - measure carefully on target machines if performance is so important in your case.

Note: passing struct by ref generally limit choices of type to arrays and fields - make sure you are willing to live with such restriction.