Does boxing cause performance issues in my code? How can I prevent boxing?
void Main()
{
AreEqual<int>(12, 13);
}
public static bool AreEqual<T>(T a, T b)
{
return a.Equals(b);
}
IL:
IL_0000: nop
IL_0001: ldc.i4.s 0C
IL_0003: ldc.i4.s 0D
IL_0005: call UserQuery.AreEqual
IL_000A: pop
IL_000B: ret
AreEqual:
IL_0000: nop
IL_0001: ldarga.s 00
IL_0003: ldarg.1
IL_0004: box 01 00 00 1B
IL_0009: constrained. 01 00 00 1B
IL_000F: callvirt System.Object.Equals
IL_0014: stloc.0 // CS$1$0000
IL_0015: br.s IL_0017
IL_0017: ldloc.0 // CS$1$0000
IL_0018: ret
Only you can answer that. It's your code, it's your code's performance. To me, that isn't a problem, to you, it might be.
By forcing the compiler to choose the correct overload. Your initial code calls
object.Equals(object)
(overridden inInt32.Equals(object)
), because that's the only method that works for every unconstrainedT
, which requires boxing of theint
argument you pass.Int32.Equals(Int32)
implementsIEquatable<T>.Equals(T)
, so put that as constraint:Which compiles to this IL:
Because the compiler will try to find the most specialized overload, in this case
IEquatable<T>.Equals(T)
.