If you must pass a value type to a method, but for some reason, it must be passed as a reference type, is it faster to:
object
ValueType
I put some example code below to demonstrate exactly what I mean:.
public class Program
{
public void Main()
{
var client = new IncrementedValueGetter();
int i = 8675309;
var byObject = client.IncrementObject(i);
var byValueType = client.IncrementValueType(i);
var byWrapper = client.IncrementWrapped(new ValueWrapper<int>(i));
}
}
public class IncrementedValueGetter
{
public int IncrementObject(object boxedValue)
{
return ((int)boxedValue) + 1;
}
public int IncrementValueType(ValueType boxedValueType)
{
return ((int) boxedValueType) + 1;
}
public int IncrementWrapped(ValueWrapper<int> valueWrapper)
{
return valueWrapper.Value + 1;
}
}
public class ValueWrapper<T>
where T: struct
{
private readonly T _value;
public ValueWrapper(T value)
{
_value = value;
}
public T Value
{
get { return _value; }
}
}
The first two are actually equivalent, and just generate the standard box
IL. The third one requires the construction of your wrapper class, which is likely more expensive than the box call.