Yes, probably the readonly option is more performant, but its debatable as to wether this performance gain is relevant or not.
Why?
The const
version will actually run the decimal constructor every time the method is invoked, while the readonly / in version will simply copy a reference to a previously created decimal instance. The latter is obviously faster.
You can verify this by simply inspecting the IL:
Const version:
IL_0001: ldc.i4.s 20
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldc.i4.0
IL_0006: ldc.i4.1
IL_0007: newobj instance void [mscorlib]System.Decimal::.ctor(int32, int32, int32, bool, uint8)
IL_000c: call instance bool C::Method2(valuetype [mscorlib]System.Decimal)
The readonly/in version:
IL_0002: ldflda valuetype [mscorlib]System.Decimal C::dd
IL_0007: call instance bool C::Method1(valuetype [mscorlib]System.Decimal&)
IL_000c: pop
That said, I'm not altogether sure why you tie const
with performance. A const
is a way to convey in your code that a given value will not change ever. const
does not mean, this value stored as a constant will be more performant when used.
Unless you really have an emprically demonstrated performance issue that is solved by this marginal (at best) optimization, a value that is logically a constant, should be a const
, and a variable that is logically a read only value should be readonly
and all other considerations should be ignored. If your case is the former then document it clearly in your code why a logically constant value is implemented as a read only field.