Which of the following code is fastest/best practice for converting some object x?
int myInt = (int)x;
or
int myInt = Convert.T
If you know that the data is definitely int then int myInt = (int)x;
should be the fastest option. Otherwise TryParse
will help you to get it right without the slowness of exceptions.
BTW :
(int) only unboxes therefore faster,
(int) IL =
.locals init (
[0] object x,
[1] int32 Y)
L_0000: ldc.i4.1
L_0001: box int32
L_0006: stloc.0
L_0007: ldloc.0
L_0008: unbox int32
L_000d: ldobj int32
L_0012: stloc.1
L_0013: ret
Convert.Toint32=
.locals init (
[0] object x,
[1] int32 Y)
L_0000: ldc.i4.1
L_0001: box int32
L_0006: stloc.0
L_0007: ldloc.0
L_0008: call object [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::GetObjectValue(object)
L_000d: call int32 [mscorlib]System.Convert::ToInt32(object)
L_0012: stloc.1
L_0013: ret