问题
One way to avoid boxing in C# is to pass the value type by reference. I have read that a generic method can also be used to avoid boxing. Although writing a generic method solely for the purpose of avoiding boxing seems to be a little extreme - if the type will always be the same.
My question is - if writing code for the best performance and to avoid boxing, is it reasonable to pass all value types (like an int) by reference - even though the method in question is only working on the object and not creating it? Are there any drawbacks to this?
回答1:
The best way to avoid boxing of value types is: just use them as values!
I think you have completely misread that reference. What it says is that using ref
parameters does not cause boxing. It does not say that it is a way to avoid
boxing.
Boxing happens when a value type is used in a reference context, such as being cast to an Object. This article says that passing parameters by reference must not be confused with the concept of reference types, but confuse them seems to be exactly what you've done.
Summary by 280Z28:
In other words, avoid the following two operations:
- Casting or assigning the value to a variable of type
object
(or passing the value as an argument for a method parameter of typeobject
). - Casting or assigning the value to a variable which is an interface type (such as
IEnumerable
), or passing the value as an argument for a method parameter which is an interface type.
There are exceptions to this rule (e.g. calling some generic methods), and there are cases where boxing can occur in other contexts, but these are the primary situations to be aware of when you are trying to avoid unnecessary boxing of value types.
来源:https://stackoverflow.com/questions/25902154/passing-c-sharp-value-type-by-reference-to-avoid-boxing