What is fastest: (int), Convert.ToInt32(x) or Int32.Parse(x)?

后端 未结 15 1168
南笙
南笙 2021-02-02 06:13

Which of the following code is fastest/best practice for converting some object x?

int myInt = (int)x;

or

int myInt = Convert.T         


        
15条回答
  •  深忆病人
    2021-02-02 06:46

    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 
    

提交回复
热议问题